乱世@小熊 2010-05-14 15:54 采纳率: 25%
浏览 215
已采纳

解析 JSON 文件的值?

I have this JSON in a file:

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": [
        "id": "valore"
    ],
    "om_points": "value",
    "parameters": [
        "id": "valore"
    ]
}

I wrote this script which prints all of the json text:

json_data=open(file_directory).read()

data = json.loads(json_data)
pprint(data)

How can I parse the file and extract single values?

转载于:https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file

  • 写回答

8条回答 默认 最新

  • hurriedly% 2010-05-14 16:10
    关注

    I think what Ignacio is saying is that your JSON file is incorrect. You have [] when you should have {}. [] are for lists, {} are for dictionaries.

    Here's how your JSON file should look, your JSON file wouldn't even load for me:

    {
        "maps": [
            {
                "id": "blabla",
                "iscategorical": "0"
            },
            {
                "id": "blabla",
                "iscategorical": "0"
            }
        ],
        "masks": {
            "id": "valore"
        },
        "om_points": "value",
        "parameters": {
            "id": "valore"
        }
    }
    

    Then you can use your code:

    import json
    from pprint import pprint
    
    with open('data.json') as f:
        data = json.load(f)
    
    pprint(data)
    

    With data, you can now also find values like so:

    data["maps"][0]["id"]
    data["masks"]["id"]
    data["om_points"]
    

    Try those out and see if it starts to make sense.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度