-2

I have a json file I am reading the file with:

with open('/content/data.json', 'r') as fh:
    for line in fh:
        text = literal_eval(line)
        print(text)
{'id': 297162425, 'id_str': '297162425'}
{'id': 1257964204650192897, 'id_str': '1257964204650192897'}
...
...
...

I have predicted output in array format: pred_ada_test = [1, 1, 0, 1, 1 ,1, 1, 1, 1 ,0]

How can I append the array to the json file like:

{'id': 297162425, 'id_str': '297162425','bot':1}
{'id': 1257964204650192897, 'id_str': '1257964204650192897','bot':1}
{'id': 934417886159896576, 'id_str': '934417886159896576','bot':0}
...
...
...

I tried to first convert the array to json:

list_to_json_array = json.dumps(pred_ada_test)
dict = {'bot':list_to_json_array}

then updated the json but got errors

It would be great if someone can help me out.

Thank you.

1 Answers1

0
with open('/content/data.json', 'r') as file:
    all_lines = file.readlines()
    line_idx = 0
    for line in all_lines:
        j = json.loads(line)
        j['bot'] = pred_ada_test[line_idx]
        all_lines[line_idx] = str(j)
        line_idx += 1


with open('/content/data.json', 'w') as file:
    file.writelines(all_lines)
Kholdarbekov
  • 973
  • 1
  • 10
  • 28