【问题标题】:How to save JSON key data to Python Variables如何将 JSON 密钥数据保存到 Python 变量
【发布时间】:2021-02-03 13:17:56
【问题描述】:

有没有办法在我的每个变量(id1-id3、id1-id3、price1-price3...)上存储我的 JSON 密钥数据(id、name、price...)

这是我的示例代码

import json

from kivy.properties import StringProperty

f = open('sample.json')
data = json.load(f)

id1 = StringProperty(None)
id2 = StringProperty(None)
id3 = StringProperty(None)

name1 = StringProperty(None)
name2 = StringProperty(None)
name3 = StringProperty(None)

price1 = StringProperty(None)
price2 = StringProperty(None)
price3 = StringProperty(None)

quantity1  = StringProperty(None)
quantity2  = StringProperty(None)
quantity3  = StringProperty(None)

for i in data:
    print(i)

这是 JSON 文件

[
  {
    "id": "p01",
    "name": "Name 1",
    "price": 1,
    "quantity": 1
  },
  {
    "id": "p02",
    "name": "Name 2",
    "price": 2,
    "quantity": 2
  },
  {
    "id": "p03",
    "name": "Name 3",
    "price": 3,
    "quantity": 3
  }
]

我打算使用更大的数据。但为了简单起见,我只是以 3 个项目为例

【问题讨论】:

  • 为什么要使用变量?您可以使用 json.loads() 简单地将 JSON 转换为 Python 字典。
  • @MuhammadYousufNoor,我将来会使用这个变量,所以我需要从 JSON 文件中提取名称、价格和数量等单个数据。我对 JSON 模块比较陌生,所以请与我裸露。

标签: python json python-3.x


【解决方案1】:

您不需要将JSON的每个值存储在一个新变量中,您可以使用python字典。

JSON and Python Dictionary

import json

#opening json file
with open("data.json") as f:
    #converting json to python dict and stroing it in data variable
    data = json.loads(f.read())

#iterating dict items and printing values
for items in data:
    print(items['id'],items['name'],items['price'])

#you can also access dict values like this
#0 is the index number.
print(data[0]['id'])
print(data[0]['name'])
print(data[0]['price'])

#similarly
print(data[1]['id'])
print(data[2]['id'])

【讨论】:

  • 谢谢你的作品,只是一个后续问题。如果我有另一个表怎么办,我应该如何访问表 2 的 dict 值?我会附上修改后的 JSON 代码
【解决方案2】:

您可以简单地使用带有python字典的json模块,如下所示:

# Import the module
import json

# String with JSON format
data_JSON =  """
[
  {
    "id": "p01",
    "name": "Name 1",
    "price": 1,
    "quantity": 1
  },
  {
    "id": "p02",
    "name": "Name 2",
    "price": 2,
    "quantity": 2
  },
  {
    "id": "p03",
    "name": "Name 3",
    "price": 3,
    "quantity": 3
  }
]
"""

# Convert JSON string to dictionary
data_dict = json.loads(data_JSON)
print(data_dict)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多