【问题标题】:Nested Dictionary JSON to Nested Dictionary in Python嵌套字典 JSON 到 Python 中的嵌套字典
【发布时间】:2018-05-31 05:24:58
【问题描述】:

我有一个 Python 字典,看起来像这样:

  {      
   "Europe": {
        "France": (10,5),
        "Germany": (15,5),
        "Italy": (5,15),
      },
"North-America": {
        "USA": (20,0),
        "CANADA": (12,4),
        "MEXICO": (14,8),
       },
 }

我想将字典保存在 JSON 文件中,以便在需要时获取数据。 我是这样做那家商店的:

with open(filename, 'a') as jsonfile:
    json.dump(dictionary, jsonfile)

问题来了。当我尝试读取存储的 json 字典时,我得到同样的错误:Python json.loads shows ValueError: Extra data

该帖子中的答案只是将不同的字典存储在一个列表中并将它们全部转储。但是如果它们是嵌套的并且是动态创建的,我不明白该怎么做。

我读取json的方式是这样的:

jsonFile = open(filename)
data = json.loads(jsonFile)
jsonFile.close()
return data

在简历中。我需要将字典从 json 文件加载到 python 中的字典。我怎样才能做到这一点?

【问题讨论】:

  • 为什么要附加到文件中?使用w 模式,JSON 本身不是可流式传输的格式。
  • 我的错。我不知道为什么我写的是 'a' 模式,而实际上是 'w' 模式
  • 加载方式是这样的:jsonFile = open(filename) data = json.loads(jsonFile) jsonFile.close() return data
  • 如果要从文件对象加载,请使用 json.load()json.loads() 仅用于解析已加载的字符串。

标签: python json dictionary


【解决方案1】:

这就是我写入 JSON 文件并从中读取的方式:

import json
from pprint import pprint

dictionary = {"Europe":
             {"France": (10,5),
              "Germany": (15,5),
              "Italy": (5,15)},

             "North-America": {
                 "USA": (20,0),
                 "CANADA": (12,4),
                 "MEXICO": (14,8)}
             }

with open("test.json", 'w') as test:
    json.dump(dictionary, test)

# Data written to test.json
with open("test.json") as test:
    dictionary = json.load(test)

pprint(dictionary)

{'Europe': {'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]},
 'North-America': {'CANADA': [12, 4], 'MEXICO': [14, 8], 'USA': [20, 0]}}
>>> 

# Accessing dictionary["Europe"]
print(dictionary["Europe"])

{'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]}
>>>

# Accessing items in dictionary["North-America"]
print(dictionary["North-America"].items())

dict_items([('USA', [20, 0]), ('CANADA', [12, 4]), ('MEXICO', [14, 8])])
>>>

编辑

# Convert your input dictionary to a string using json.dumps()
data = json.dumps(dictionary)

# Write the string to a file
with open("test.json", 'w') as test:
    test.write(data)

# Read it back
with open("test.json") as test:
    data = test.read()

# decoding the JSON to dictionary
d = json.loads(data)

print(type(d))

<class 'dict'>
>>> 

现在你可以像普通字典一样使用它了:

>>> d["Europe"]
{'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]}
>>> d["North-America"].items()
dict_items([('USA', [20, 0]), ('CANADA', [12, 4]), ('MEXICO', [14, 8])])
>>>

【讨论】:

  • 我明白了。我会尝试并告诉我我有什么结果。
  • 非常感谢。这就是问题所在,我在写和读时没有进行编码/解码过程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 2018-01-29
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多