Why can't Python parse this JSON data?

后端 未结 9 2643
傲寒
傲寒 2020-11-21 05:06

I have this JSON in a file:

{
    \"maps\": [
        {
            \"id\": \"blabla\",
            \"iscategorical\         


        
9条回答
  •  不要未来只要你来
    2020-11-21 05:15

    Your data.json should look like this:

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

    Your code should be:

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

    Note that this only works in Python 2.6 and up, as it depends upon the with-statement. In Python 2.5 use from __future__ import with_statement, in Python <= 2.4, see Justin Peel's answer, which this answer is based upon.

    You can now also access single values like this:

    data["maps"][0]["id"]  # will return 'blabla'
    data["masks"]["id"]    # will return 'valore'
    data["om_points"]      # will return 'value'
    

提交回复
热议问题