严格的JSON格式
用Python处理/生成JSON文件
先看个python list/array:
my_list = [ {"Jerry": {"job": "comedian", "age": 34, "married": True,},}, {"Elaine": {"job": "housewife", "age": 32, "married": False,},} ] print(my_list)
运行结果为:
[{'Jerry': {'job': 'comedian', 'age': 34, 'married': True}}, {'Elaine': {'job': 'housewife', 'age': 32, 'married': False}}]
注意看区别:
一、双引号,变成了单引号;
二、原代码my_list中,在True,False后面,我特地添加了两个额外的逗号,,而这些逗号在python运行后,被忽略了。所以以后建议不要加。而且,如果加了,在用JSON load这个list时,会报错
把上面的运行结果
[{'Jerry': {'job': 'comedian', 'age': 34, 'married': True}}, {'Elaine': {'job': 'housewife', 'age': 32, 'married': False}}]
保存到source.json文件中,注意把True,False改为true, false
import json with open("source.json") as f: data = json.load(f) with open("target.json", 'w', encoding='utf-8') as file: json.dump(data, file, indent=4, ensure_ascii=False)
运行上面的代码,生成的target.json文件里,会得到:
[ { "jerry": { "job": "comedian", "age": 34, "married": true } }, { "Elaine": { "job": "housewife", "age": 32, "married": false } } ]