℡Wang Yan 2010-05-14 15:54 采纳率: 50%
浏览 236
已采纳

解析 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条回答 默认 最新

  • 程序go 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条)

报告相同问题?