熊猫:json_normalize及其行为

时间:2019-12-10 11:46:35

标签: python json python-3.x pandas

我目前无法解析示例JSON。看起来像这样:

import json
from pandas.io.json import json_normalize
sample_data = '''
[
    {
        "productid": 123456,
        "name": "produkt 1",
        "shortname": "p1",
        "owner": {
            "name": "Peewee Herman",
            "orgId": "ACME Inc.",
            "shortname": "ph"
        }
    }
]
'''

加载数据没问题:

> json.loads(sample_data)

[{'productid': 123456,
  'name': 'produkt 1',
  'shortname': 'p1',
  'owner': {'name': 'Peewee Herman', 'orgId': 'ACME Inc.', 'shortname': 'ph'}}]

但是当我尝试使用json_normalize遵循路径时,我将值的每个字符都返回为行:

> json_normalize(json.loads(sample_data), ['owner', 'orgId'])

    0
0   A
1   C
2   M
3   E
4   
5   I
6   n
7   c
8   .

这个更好一点:

> json_normalize(json.loads(sample_data), meta=[[["owner", "shortname"]], "name"])

    productid   name    shortname   owner.name  owner.orgId     owner.shortname
0   123456  produkt 1   p1  Peewee Herman   ACME Inc.   ph

在这种情况下,我希望仅显示“名称”和“ owner.shortname”,而不显示整个内容。

结果应为(示例):

productId name shortname owner.name

有人对此查询有解决方案吗?

0 个答案:

没有答案