简体   繁体   中英

Python Error: json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2) when json.loads a valid json file

I am trying to load a valid json file (according to jsonlint.com) into python to then index it into elasticsearch.

MY CODE:

file = open(json_file)
i=1
json_data = [json.loads(line) for line in file]
print(json_data)

ERROR I AM RECEIVING:

json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2)

I have checked other's solutions which focus on the invalidity of the json file but mine is completely valid.

SHORTENED VERSION OF MY JSON FILE:

[
  {"sepalLength": 5.1, "sepalWidth": 3.5, "petalLength": 1.4, "petalWidth": 0.2, "species": "setosa"},
  {"sepalLength": 4.9, "sepalWidth": 3.0, "petalLength": 1.4, "petalWidth": 0.2, "species": "setosa"},
  {"sepalLength": 4.7, "sepalWidth": 3.2, "petalLength": 1.3, "petalWidth": 0.2, "species": "setosa"},
  {"sepalLength": 4.6, "sepalWidth": 3.1, "petalLength": 1.5, "petalWidth": 0.2, "species": "setosa"}
]

I have no idea what seems to be the problem here.

Your list comprehension is trying to load as many objects as there are lines in your file, but there is just one file. Use this:

import json

with open(json_file, 'r') as f:
    json_data = [line for line in json.load(f)]
    print(json_data)

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