简体   繁体   中英

Read certain lines of a JSON file?

I have a JSON file with 50,000 lines. Every line is an object.

I would like to read in the first 5 lines.

The below code keeps giving me an error that I'm trying to load a list. What am I missing?

f = open('./flights.json', 'r').readlines()[:5]
dict = json.loads(f)

If every line is an object, you have a JSONL or JSON Lines format file, not a JSON file. json.loads will parse a single string that represents a single valid JSON value. It will not accept a list. This works (I have taken liberty to rename your variables appropriately):

five_values = [json.loads(line) for line in five_lines]

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