首页 > 解决方案 > 如何从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],
  (...)
]"

标签: pythonjsonpython-3.x

解决方案


假设您的data对象是一个简单的字典或列表,您需要做的就是:

with open(output_path, 'w') as f:
    json.dump(data, f, sort_keys=True, indent=4)

这将正确转储到输出文件。


推荐阅读