Why can't Python parse this JSON data?

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

I have this JSON in a file:

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


        
相关标签:
9条回答
  • 2020-11-21 05:27

    Your data is not valid JSON format. You have [] when you should have {}:

    • [] are for JSON arrays, which are called list in Python
    • {} are for JSON objects, which are called dict in Python

    Here's how your JSON file should look:

    {
        "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.

    0 讨论(0)
  • 2020-11-21 05:39

    "Ultra JSON" or simply "ujson" can handle having [] in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as, [{[{}]}, {}, [], etc...] ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.

    You can find ujson in the Python package index and the API is almost identical to Python's built-in json library.

    ujson is also much faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.

    0 讨论(0)
  • 2020-11-21 05:39

    There are two types in this parsing.

    1. Parsing data from a file from a system path
    2. Parsing JSON from remote URL.

    From a file, you can use the following

    import json
    json = json.loads(open('/path/to/file.json').read())
    value = json['key']
    print json['value']
    

    This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python

    0 讨论(0)
提交回复
热议问题