如何以漂亮的打印样式在 JSON 中编写数据框?

how to write dataframe in JSON in pretty print style?

我想将我的数据帧转换为 json 并以漂亮的打印格式将其转储到文件中。 我试过了 -

df.to_json(r'C:\users\madhur\Desktop\example.json,'orient = 'index')

以上代码在 json 中转储,但在一行中。

我也试过了

import json
hello = df.to_json(orient = 'index')
with open(r'C:\users\madhur\Desktop\example.json','a') as f:
    json.dump(hello,f,indent=4,sort_keys=True)

但是上面的代码给出了单行输出,输出在双引号之前有一个 '\'

输出看起来像 -

"{\"17668620_INCOLL\":{\"DRWECNTRY\":\"NEW ZEALAND........"

如果有人对此查询有任何建议、答案或需要更多信息,请comment/answer。

注意 - 我使用的是 Python 3.6

可以直接传indent = int :

df.to_json(r'example.json', orient='index', indent=2 )

如果你想简单地从 REPL

复制粘贴一些东西,请使用 df.to_dict(orient='records')