如何在这个格式化为dictionary的JSON文件中读取



所以我正在学习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库。

从json到字典

x = json.loads(YourDictionary)

从字典到json

y = json.dumps(YourDictionary)

这里有一个链接参考:https://www.w3schools.com/python/python_json.asp

最新更新