如何使用Python从JSON文件创建销售表

时间:2019-03-18 17:35:42

标签: python json

我有一个像这样的JSON文件,并且在生成带有以下内容的表时遇到了麻烦 列为名称,号码,国家/地区代码(价格中的第一项),货币

{"a": [{"Name": "name1",
  "number": "number1",
  "defaultPrice": {"p": "232", "currency": "CAD"},
  "prices": {"DZ": {"p": "62", "currency": "RMB"},
   "AU": {"p": "73", "currency": "AUD"},
  "lg": "en"}},
 {"Name": "name2",
  "number": "number2",
  "defaultPrice": {"p": "233", "currency": "CAD"},
  "prices": {"DZ": {"p": "63", "currency": "RMB"},
  "US": {"p": "72", "currency": "USD"},
  "Lg": "en"}}]}

问题是我仅在解析时得到回溯:

Traceback (most recent call last):
  File "test.py", line 49, in <module>
    val = ast.literal_eval(mystr)
  File "/anaconda3/lib/python3.7/ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/anaconda3/lib/python3.7/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 38
 SyntaxError: unexpected EOF while parsing

我用的是

mystr='''
....
'''
val = ast.literal_eval(mystr)
val1 = json.loads(json.dumps(val))
val2 = val1['a'][0]['Name']
print pd.DataFrame(val2, columns=["Name"])

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

要使用json模块将文件加载到字典中,json.load将使用文件句柄:

import json

with open('yourfile.json') as fh:
    val = json.load(fh)

type(val)
dict

# to get the structure you're looking for
val1 = val.get('a')

type(val1)
list
# Now you can iterate over it, or throw it into pandas if you want a
# table-like data structure

val1[0].keys()
dict_keys(['Name', 'number', 'defaultPrice', 'prices'])

使用字符串方法

您也可以使用原始帖子中的字符串方法来做到这一点:

import json

with open('yourfile.json') as fh:
    mystr = fh.read()

# Note, this is json.loads, which takes a string arg not a file handle
val = json.loads(mystr)

val
{'a': [{'Name': 'name1', 'number': 'number1', 'defaultPrice': {'p': '232', 'currency': 'CAD'}, 'prices': {'DZ': {'p': '62', 'currency': 'RMB'}, 'AU': {'p': '73', 'currency': 'AUD'}, 'lg': 'en'}}, {'Name': 'name2', 'number': 'number2', 'defaultPrice': {'p': '233', 'currency': 'CAD'}, 'prices': {'DZ': {'p': '63', 'currency': 'RMB'}, 'US': {'p': '72', 'currency': 'USD'}, 'Lg': 'en'}}]}

type(val)
dict


# To put this into pandas

import pandas as pd

val1 = val.get('a')

df = pd.DataFrame(val1)

df如下所示:

    Name                        ...                                                                     prices
0  name1                        ...                          {'DZ': {'p': '62', 'currency': 'RMB'}, 'AU': {...
1  name2                        ...                          {'DZ': {'p': '63', 'currency': 'RMB'}, 'US': {...

[2 rows x 4 columns]

大熊猫会将列名作为字典列表中的键