Skip to content

BUG: non-iterable value in meta raise error in json_normalize #31524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 33 commits into from
Mar 11, 2020

Conversation

charlesdong1991
Copy link
Member

@charlesdong1991 charlesdong1991 commented Jan 31, 2020

@pep8speaks
Copy link

pep8speaks commented Jan 31, 2020

Hello @charlesdong1991! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻

Comment last updated at 2020-03-11 07:54:57 UTC

@WillAyd
Copy link
Member

WillAyd commented Jan 31, 2020

Can you add a whatsnew for v1.0.1?

@charlesdong1991
Copy link
Member Author

oops, i was editing whatsnew just now 😅

@charlesdong1991
Copy link
Member Author

emm,

self = <pandas.tests.io.json.test_normalize.TestNestedToRecord object at 0x14ab9d208>

    def test_meta_non_iterable(self):
        # GH 31507
        data = """[{"id": 99, "data": [{"one": 1, "two": 2}]}]"""
    
        result = json_normalize(json.loads(data), record_path=["data"], meta=["id"])
        expected_values = [[1, 2, "99"]]
        columns = ["one", "two", "id"]
        expected = DataFrame(expected_values, columns=columns)
>       tm.assert_frame_equal(result, expected)

pandas/tests/io/json/test_normalize.py:761: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
pandas/_libs/testing.pyx:65: in pandas._libs.testing.assert_almost_equal
    cpdef assert_almost_equal(a, b,
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

>   raise_assert_detail(obj, msg, lobj, robj)
E   AssertionError: DataFrame.iloc[:, 2] (column name="id") are different
E   
E   DataFrame.iloc[:, 2] (column name="id") values are different (100.0 %)
E   [left]:  [99]
E   [right]: [99]

is there a bug in assert_frame_equal? 🤔 will check it out tomorrow

data = """[{"id": 99, "data": [{"one": 1, "two": 2}]}]"""

result = json_normalize(json.loads(data), record_path=["data"], meta=["id"])
expected_values = [[1, 2, "99"]]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The expected value here should be 99 not "99" (probably cause of CI error)

@@ -749,3 +749,13 @@ def test_series_non_zero_index(self):
}
)
tm.assert_frame_equal(result, expected)

def test_meta_non_iterable(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you move this near the other test

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved! and wait for @WillAyd comment on the other one

result = js # type: ignore
if isinstance(spec, list):
for field in spec:
result = result[field]
else:
result = result[spec]

if not isinstance(result, Iterable):
# GH 31507 iterable limit should only be used on record, not meta
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a code smell to add this. so it seems that result can be null, iterabe, or a scalar? if its a scalar what is the return value here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you mean [99]? then will still return 99

i think this Iterable should only restrict if specifying record_path, but not for meta? Am I right about the behaviour here @WillAyd ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do agree that this is getting a little strange, especially since there is inspection of meta on line 273 of the same module and we are essentially repeating that here with a boolean indicator being manually supplied

@charlesdong1991 do you see a way to more logically order this function so we don't have to use this bool indicator?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for your reply! @WillAyd

I will think about it a bit, i feel the patch for that Iterable in this _pull_field has code smell a bit because it is used for two cases which have different requirements

Copy link
Member Author

@charlesdong1991 charlesdong1991 Feb 4, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

especially since there is inspection of meta on line 273 of the same module and we are essentially repeating that here with a boolean indicator being manually supplied

i just take a look again at the current codebase, seems that line 273 and onwards you referred is to validate/transform the key which is assigned to meta not the value the key associated with, in this case, key is id (and we could either specify it as [id] or id or more complex cases with nested list, and this part of code will deal with it), however, the code in _pull_field is to pull the value out, and in this case, the value is 99, and for record_path the value should be an Iterable, while for meta it does not necessarily be the case, and therefore I think the patch added to check the type should only work for values of which the element of record_path point to, not for meta, maybe I miss some functionalities of either of them? @WillAyd @jreback

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@charlesdong1991 does splitting this into separate functions for record_path vs meta and just using this as a base for those functions make things cleaner?

@jreback jreback added Bug IO JSON read_json, to_json, json_normalize labels Feb 1, 2020
@charlesdong1991
Copy link
Member Author

charlesdong1991 commented Feb 11, 2020

@WillAyd @jreback I slightly changed the change made in #30145 and think this should be the cleaner solution to fix this bug, please take a look and any feedback is very appreciated!

@charlesdong1991
Copy link
Member Author

many thanks for your quick response @WillAyd

I will leave this PR then, and feel free to still take a look and see if anything else you want to see improvements. I will rebase once the fix PR is merged

@charlesdong1991 charlesdong1991 requested a review from WillAyd March 5, 2020 21:27
@charlesdong1991
Copy link
Member Author

any further feedbacks? @WillAyd

I think this would be nice to be included in 1.0.2 as it seems impact many users based on the responds under the Issue

result = js # type: ignore
def _pull_field(js: Dict[str, Scalar], spec: Union[List, str]) -> Scalar:
"""Internal function to pull field"""
result = js
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did this need to change?

Copy link
Member Author

@charlesdong1991 charlesdong1991 Mar 10, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

emm, this is because i moved type: ignore to result = result[field] below, because without type: ignore, this result = result[field] will raise an error in type annotation which complains the incompatible assignment. And after moving it below, this one does not seem needed.

@WillAyd any thoughts on this?

Copy link
Contributor

@TomAugspurger TomAugspurger left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, other than a question about the release note.

@charlesdong1991
Copy link
Member Author

@TomAugspurger thanks for your quick feedback, however, maybe something went wrong with github, your question about release note is not presented, could you please rewrite your question? thanks!

@TomAugspurger
Copy link
Contributor

Strange. Is this fixing a regression? If so, the note should be towards the top of 1.0.2.rst with the other regression fixes.

@charlesdong1991
Copy link
Member Author

charlesdong1991 commented Mar 10, 2020

thanks! @TomAugspurger
this is not a regression issue fix IMHO, and maybe it is better to keep it in I/O section?

@TomAugspurger
Copy link
Contributor

TomAugspurger commented Mar 10, 2020 via email

Copy link
Contributor

@jreback jreback left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

result = js # type: ignore
if isinstance(spec, list):
for field in spec:
result = result[field]
result = result[field] # type: ignore
Copy link
Member

@WillAyd WillAyd Mar 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you advise specifically what the error is? I realize we want to get this in for 1.0.2 so not going to block, but I still think this code is suspect (not from your change per se - just a historical artifact) so I'd hate to suppress a warning about another bug that this fix could be introducing

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took a look at this locally; I think if you revert some of the other changes here you won't need the ignore. Suggested separately

Copy link
Member Author

@charlesdong1991 charlesdong1991 Mar 11, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, the error is:

error: Incompatible types in assignment (expression has type "Union[str, int, float, bool, Any, Any, Any, Any]", variable has type "Dict[str, Union[str, int, float, bool, Any, Any, Any, Any]]")

as said, this is because result = result[field], and result is a Dict while the value of result is not, so there is a conflict. And having Any instead of Scalar could fix the issue

result = js # type: ignore
if isinstance(spec, list):
for field in spec:
result = result[field]
result = result[field] # type: ignore
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took a look at this locally; I think if you revert some of the other changes here you won't need the ignore. Suggested separately

@@ -226,14 +227,26 @@ def _json_normalize(
Returns normalized data with columns prefixed with the given string.
"""

def _pull_field(js: Dict[str, Any], spec: Union[List, str]) -> Iterable:
def _pull_field(js: Dict[str, Scalar], spec: Union[List, str]) -> Scalar:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def _pull_field(js: Dict[str, Scalar], spec: Union[List, str]) -> Scalar:
def _pull_field(js: Dict[str, Any], spec: Union[List, str]) -> Union[Scalar, Iterable]:

result = js # type: ignore
if isinstance(spec, list):
for field in spec:
result = result[field]
result = result[field] # type: ignore
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
result = result[field] # type: ignore
result = result[field]

else:
result = result[spec]
result = result[spec] # type: ignore
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
result = result[spec] # type: ignore
result = result[spec]

result = result[spec] # type: ignore
return result

def _pull_records(js: Dict[str, Scalar], spec: Union[List, str]) -> Iterable:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def _pull_records(js: Dict[str, Scalar], spec: Union[List, str]) -> Iterable:
def _pull_records(js: Dict[str, Any], spec: Union[List, str]) -> Iterable:

@jreback jreback added this to the 1.0.2 milestone Mar 11, 2020
@charlesdong1991
Copy link
Member Author

Sorry about the mess I made on the type annotation and function naming @WillAyd

I have committed a fix following ur suggestion, pls let me know your thoughts, and I will try to update PR asap to get this done before release.

@TomAugspurger
Copy link
Contributor

CI is passing, so I'm planning to merge this in an hour or so if there aren't any objections. We can fixup annotations later if needed.

Copy link
Member

@WillAyd WillAyd left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm. Appears the annotations were already cleaned up

@WillAyd WillAyd merged commit 983fae6 into pandas-dev:master Mar 11, 2020
@WillAyd
Copy link
Member

WillAyd commented Mar 11, 2020

Thanks @charlesdong1991 . Great job seeing this through

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug IO JSON read_json, to_json, json_normalize
Projects
None yet
Development

Successfully merging this pull request may close these issues.

json_normalize in 1.0.0 with meta path specified - expects iterable
7 participants