Perché Python non può analizzare questi dati JSON?

Ho questo JSON in un file:

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

Ho scritto questo script per stampare tutti i dati JSON:

import json
from pprint import pprint

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

pprint(data)

Questo programma solleva però un'eccezione:

{{69768}};

Traceback (most recent call last):
  File "<pyshell#1>", line 5, in <module>
    data = json.load(f)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)

Come posso analizzare il JSON ed estrarre i suoi valori?

Soluzione

I tuoi dati non sono in formato JSON valido. Hai [] quando dovresti avere {}:

  • [] sono per gli array JSON, che sono chiamati list in Python
  • {} sono per gli oggetti JSON, che sono chiamati dict in Python

Ecco come dovrebbe apparire il tuo file JSON:

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

Poi puoi usare il tuo codice:

import json
from pprint import pprint

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

pprint(data)

Con i dati, ora puoi anche trovare i valori in questo modo:

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

Provateli e vedete se iniziano ad avere senso.

Commentari (14)

Il tuo data.json dovrebbe assomigliare a questo:

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

Il tuo codice dovrebbe essere:

import json
from pprint import pprint

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

Notate che questo funziona solo in Python 2.6 e superiori, poiché dipende dal with-statement. In Python 2.5 usa from __future__ import with_statement, in Python

Commentari (7)
data = []
with codecs.open('d:\output.txt','rU','utf-8') as f:
    for line in f:
       data.append(json.loads(line))
Commentari (5)