首页 > 解决方案 > 如何将数组附加到json?

问题描述

我有一个 json 文件,我正在读取该文件:

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'}
...
...
...

我以数组格式预测输出: pred_ada_test = [1, 1, 0, 1, 1 ,1, 1, 1, 1 ,0]

如何将数组附加到 json 文件中,例如:

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

我尝试先将数组转换为 json:

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

然后更新了json但出现错误

如果有人可以帮助我,那就太好了。

谢谢你。

标签: pythonjsonpython-3.x

解决方案


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)

推荐阅读