简体   繁体   中英

Python: why does repeat of json.load cause error

 with open(LATEST_UPDATE_FULL_PATH) as JSON_FILE_UPDATE:
                    JSON_DATA_UPDATE = json.load(JSON_FILE_UPDATE)
                    JSON_DATA_UPDATE = json.load(JSON_FILE_UPDATE)

why does doing "load" twice causes the following below? Is there a handle on this file? I could not find anything to release JSON_FILE_UPDATE.

Traceback (most recent call last):
  File "PhthonScript", line 69, in <module>
    JSON_DATA_UPDATE = json.load(JSON_FILE_UPDATE)
  File "...\PythonByMiniconda3\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "...\PythonByMiniconda3\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "...\PythonByMiniconda3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "...\PythonByMiniconda3\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

try this:

JSON_DATA_UPDATE = json.loads(JSON_FILE_UPDATE)

once it is loaded, then the file converted to json. cannot convert json to json.

another way, this may work on string to json:

import ast

file = """{
  "students": [
    {
      "name": "Millie Brown",
      "active": False,
      "rollno": 11
    },
    {
      "name": "Sadie Sink",
      "active": True,
      "rollno": 10
    }
  ]
}"""

print(type(file))
dict = ast.literal_eval(file)
print(type(dict))

dict['students'][0]['name']  would be "Millie Brown"
dict['students'][1]['active']  would be True

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