【问题标题】:How to read in this JSON file formatted as a dictonary?如何读入这个格式化为字典的 JSON 文件?
【发布时间】: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
                }
            ]

 },

【问题讨论】:

标签: python json file dictionary


【解决方案1】:

你想要 json 库。

从 json 到字典

x = json.loads(YourDictionary)

从字典到 json

y = json.dumps(YourDictionary)

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

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多