如何在Notepad ++中为使用Python保存的JSON正确解析JSON?

问题描述

我有一个dict,它在JSON中另存为Python,如下面的代码所示。

import json
# https://intellipaat.com/blog/tutorial/python-tutorial/python-json/
person_dict = {
  "name": "xxxx","age": 30,"married": True,"divorced": False,"children": ("Ann","Billy"),"pets": None,"cars": [
    {"model": "BMW 230","mpg": 27.5},{"model": "Ford Edge","mpg": 24.1}
  ]
}


tt_json=json.dumps(person_dict)
with open ('data.json','w') as f:
  json.dump (tt_json,f)

然后,我想查看data.json中的Notepad++。但是,使用插件JavaScript Map ParserJSON Viewer,JSON如下所示

enter image description here

我希望插件JavaScript Map ParserJSON Viewer呈现如下的JSON。

enter image description here

问题似乎是由于用Python保存的JSON包含在双引号"{ ... }"中。

"\"\\n{\\n  \\\"name\\\": \\\"xxxx\\\",\\n  \\\"age\\\": 30,\\n  \\\"married\\\": True,\\n  \\\"divorced\\\": False,\\n  \\\"children\\\": (\\\"Ann\\\",\\\"Billy\\\"),\\n  \\\"pets\\\": None,\\n  \\\"cars\\\": [\\n    {\\\"model\\\": \\\"BMW 230\\\",\\\"mpg\\\": 27.5},\\n    {\\\"model\\\": \\\"Ford Edge\\\",\\\"mpg\\\": 24.1}\\n  ]\\n}\\n\""

我可以知道如何在Notepad ++中或通过调整JSON在Python中的保存方式来解决此问题。

请注意,此JSON将保存在Python中,以后需要在Notepad ++中进行一些手动修改,然后在Python中重新打开。

p.s。 感谢venky。使用建议的解决方案,JSON在Notepad ++中作为单个衬纸呈现。

enter image description here

但是,可以使用JSTool通过以下设置来修饰JSON:

enter image description here

,它将显示如下的JSON:

enter image description here

解决方法

您要将字典转换为JSON,然后使用JSON.dump两次再次转换为JSON。 写入文件时只需使用一次。

import json
person_dict = {
  "name": "xxxx","age": 30,"married": True,"divorced": False,"children": ("Ann","Billy"),"pets": None,"cars": [
    {"model": "BMW 230","mpg": 27.5},{"model": "Ford Edge","mpg": 24.1}
  ]
}

with open ('data.json','w') as f:
    json.dump(person_dict,f)

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...