import jsonlines
with jsonlines.open('example.jsonl', 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
The jsonl_f is the reader and can be used directly. It contains the lines in the json file.
Answer from NargesooTv on Stack Overflow
» pip install jsonlines
Videos
import jsonlines
with jsonlines.open('example.jsonl', 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
The jsonl_f is the reader and can be used directly. It contains the lines in the json file.
Simply:
import jsonlines
with jsonlines.open("json_file.json") as file:
data = list(file.iter())
Your input appears to be a sequence of Python objects; it certainly is not valid a JSON document.
If you have a list of Python dictionaries, then all you have to do is dump each entry into a file separately, followed by a newline:
import json
with open('output.jsonl', 'w') as outfile:
for entry in JSON_file:
json.dump(entry, outfile)
outfile.write('\n')
The default configuration for the json module is to output JSON without newlines embedded.
Assuming your A, B and C names are really strings, that would produce:
{"index": 1, "met": "1043205", "no": "A"}
{"index": 2, "met": "000031043206", "no": "B"}
{"index": 3, "met": "0031043207", "no": "C"}
If you started with a JSON document containing a list of entries, just parse that document first with json.load()/json.loads().
The jsonlines package is made exactly for your use case:
import jsonlines
items = [
{'a': 1, 'b': 2},
{'a', 123, 'b': 456},
]
with jsonlines.open('output.jsonl', 'w') as writer:
writer.write_all(items)
(Yes, I wrote it years after you posted your original question.)
You have a JSON Lines format text file. You need to parse your file line by line:
import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.
Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.
If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.
In case you are using pandas and you will be interested in loading the json file as a dataframe, you can use:
import pandas as pd
df = pd.read_json('file.json', lines=True)
And to convert it into a json array, you can use:
df.to_json('new_file.json')
» pip install jsonline