【发布时间】:2020-03-24 15:41:04
【问题描述】:
因此,我正在学习 Python,并且正在开展一个涉及跟踪自动售货机的项目。我得到了 JSON 文件来获取我需要的信息,但我不知道如何读入。我的老师说它的格式可以很容易地用每个自动售货机插槽作为字典来读,但我对字典很不熟悉并且不明白该怎么做。如果有人能快速给我一个如何阅读本文的示例,我将不胜感激,因为我什至不知道从哪里开始。
这是 JSON 文件的一部分:
{
"contents": [
{
"row": "A",
"slots": [
{
"current_stock": 2,
"item_name": "Coke",
"item_price": 1.75,
"last_stock": 3,
"slot_number": 1
},
{
"current_stock": 0,
"item_name": "Coke",
"item_price": 1.75,
"last_stock": 6,
"slot_number": 2
},
{
"current_stock": 1,
"item_name": "Coke",
"item_price": 1.75,
"last_stock": 2,
"slot_number": 3
},
{
"current_stock": 3,
"item_name": "Coke",
"item_price": 1.75,
"last_stock": 3,
"slot_number": 4
},
{
"current_stock": 2,
"item_name": "Coke",
"item_price": 1.75,
"last_stock": 2,
"slot_number": 5
},
{
"current_stock": 0,
"item_name": "Coke",
"item_price": 1.75,
"last_stock": 5,
"slot_number": 6
},
{
"current_stock": 6,
"item_name": "Coke Zero",
"item_price": 1.75,
"last_stock": 8,
"slot_number": 7
},
{
"current_stock": 2,
"item_name": "Coke Zero",
"item_price": 1.75,
"last_stock": 4,
"slot_number": 8
},
{
"current_stock": 4,
"item_name": "Coke Zero",
"item_price": 1.75,
"last_stock": 7,
"slot_number": 9
}
]
},
【问题讨论】:
-
有一个内置模块来解析 JSON:docs.python.org/3.8/library/json.html
-
请注意,JSON 对象和 Python
dict文字看起来非常相似。它可能很方便,但也可能造成混乱。 -
您好,欢迎来到 stackoverflow!答案stackoverflow.com/a/20199213/1723886 解释了如何加载 json 文件。它的作用是给你一本字典。
-
这能回答你的问题吗? Reading JSON from a file?
标签: python json file dictionary