python - 如何将数组附加到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但出现错误
如果有人可以帮助我,那就太好了。
谢谢你。
解决方案
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)
推荐阅读
- clojure - 转换为 clojure 线程运算符
- swift - 斯威夫特:静态初始化()
- php - 在循环内使用 laravel elequent
- sql - 怎样给球员排名最高分
- mongodb - MongoDB:超时后Mongoclient连接失败并出现错误No route to host
- r - 根据 dplyr 中多个数据帧中的值将列添加到数据帧
- html - 如何对齐两个弹性框以相互跟随?
- botframework - 枚举 LUIS 实体
- php - 在php中使用具有特定默认参数的函数?
- amazon-ec2 - 当我尝试使用带有 terraform 的 AWS 用户数据在 Windows 2012 R2 中设置 WinRM 时出现错误