简体   繁体   中英

Load pretty printed JSON from file into python?

I have a large JSON document stored in a pretty-print format to file, where the file looks like:

$ nano data.json

{
"type" : "object",
"properties" : {
  "price" : {"type" : "number"},
  "name" : {"type" : "string"},
  },
}

The traditional ways I've found for reading such json files, such as...

with open('data.json', 'r') as handle:
    data = json.load(handle)

and...

json_data=open('data.json','r')
data = json.load(json_data)
json_data.close()

and...

data = []
with open('data.json') as f:
    for line in f:
        data.append(json.loads(line))

and...

ss = ''
with open('data.json', 'r') as f:
    for line in f:
        ss += ''.join(line.strip())

data = json.loads(ss.decode("utf-8","replace"))

...seem to only work for single-string, not pretty-print formatted JSON.

How would I load JSON of this format from a file? The errors I keep getting when trying these formats are...

Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 1 column 250 (char 250)

ValueError: Expecting , delimiter: line 9 column 13 (char 310)

For anyone else finding this in the future googling things similar to what I did when I posted this---you may think your error is in the loading, but mine as above was actually in the JSON itself, rather than the loading (as Martijn Pieters pointed out). I was copying the schema from the jsonschema python project---but this, it turned out, was not JSON, but a deceptively similar-looking python dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM