python - 如何从json修复'\ n'?
问题描述
我正在尝试修复使用名为的函数创建的 json 文件
create
. 但我不断得到这种格式:
电流输入
"[\n [\n 1,\n 1111,\n \"2019-07-17\",\n \"11:00:00\",\n \"12:00:00\",\n 505\n ],\n [\n 2,\n 2233,\n \"2019-05-03\",\n \"16:00:00\",\n \"17:30:00\",\n 205\n ],\n [\n 3,\n 2245,\n \"2019-05-04\",\n \"17:30:00\",\n \"19:00:00\",\n 204\n ],\n [\n 4,\n 1354,\n \"2019-05-05\",\n \"8:00:00\",\n \"9:30:00\",\n 206\n ]\n]"
我尝试了以下代码:
def create(data):
"""creates an outputfile"""
data_filename="iss_tui_records.js"
with open(data_filename, "w", encoding="utf-8") as file_handle:
json.dump(data, file_handle)
data=fetchall() #from mysql-connector-python
for e in data:
data_json=(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '), default=str))
print("export",datos_json)
create(data_json)
预期输出
"[
[1,1111,2019-07-17,11:00:00,12:00:00,505],
[2,2233,2019-05-03,16:00:00,17:30:00",205],
(...)
]"
解决方案
假设您的data
对象是一个简单的字典或列表,您需要做的就是:
with open(output_path, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4)
这将正确转储到输出文件。
推荐阅读
- javascript - Javascript 在鼠标状态为“保持”时调用函数
- react-native - 更改子组件的 props 值导致渲染过多
- matlab - Matlab:细胞结肠的新希望?
- reactjs - 在 Ubuntu 20.04 中安装 mongoDB 失败
- google-apps-script - 谷歌脚本编辑器:通过动态“X”复制和粘贴特定数据范围?
- javascript - 为什么 getElementById 不被识别?
- python - 如何在 numpy python 中用 antoher 增加一个向量
- google-apps-script - 用户对此配置文件没有足够的权限。- 谷歌分析 API v4
- sql-server - 在同步提交模式下使用只读副本,查询是否有可能在辅助节点上获得与主节点不同的结果?
- mapstruct - mapstruct空检查导致spotbug错误