标签:.json 转化 default enc name json格式 rip 交互 info
import json dic = {"name": "Tom", "age": 18, "hobby": "篮球", 1: False, 2: None} s = json.dumps(dic, ensure_ascii=False) print(s) # {"name": "Tom", "age": 18, "hobby": "篮球", "1": false, "2": null}
s = ‘{"name": "Tom", "age": 18, "hobby": "篮球", "1": false, "2": null}‘ dic = json.loads(s) print(dic) # {‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘篮球‘, ‘1‘: False, ‘2‘: None}
将python字典转换成json字符串,并写入文件中
import json dic = {"name": "Tom", "age": 18, "hobby": "篮球", 1: False, 2: None} f = open("1.json", "w", encoding="utf-8") # 把对象打散成json写入到文件中 json.dump(dic, f, ensure_ascii=False, indent=4) f.close()
结果:
import json f = open("1.json", encoding="utf-8") dic = json.load(f) f.close() print(dic) # {‘name‘: ‘Tom‘, ‘age‘: 18, ‘hobby‘: ‘篮球‘, ‘1‘: False, ‘2‘: None}
我们可以向同一文件中写入多个json字符串,但是json文件中内容是一行内容。此时读取时无法读取。
import json lst = [{"a": 1}, {"b": 2}, {"c": 3}] f = open("2.json", "w") for el in lst: json.dump(el, f) f.close()
结果:
f = open("2.json") dic = json.load(f) 结果: json.decoder.JSONDecodeError: Extra data: line 1 column 9 (char 8)
改用dumps和loads,对每一行分别做处理
import json lst = [{"a": 1}, {"b": 2}, {"c": 3}] f = open("2.json", "w") for el in lst: s = json.dumps(el) + "\n" f.write(s) f.close()
结果:
f = open("2.json") for line in f: dic = json.loads(line.strip()) print(dic) f. close()
结果:
{‘a‘: 1}
{‘b‘: 2}
{‘c‘: 3}
import json class Person(object): def __init__(self, name, age): self.name = name self.age = age p = Person("Tom", 18) def func(obj): return {"name": obj.name, "age": obj.age} s = json.dumps(p, default=func) print(s) # {"name": "Tom", "age": 18}
class Person(object): def __init__(self, name, age): self.name = name self.age = age s = ‘{"name": "Tom", "age": 18}‘ def func(dic): return Person(dic["name"], dic["age"]) p = json.loads(s, object_hook=func) print(p.name, p.age) # Tom 18
标签:.json 转化 default enc name json格式 rip 交互 info
原文地址:https://www.cnblogs.com/ipython-201806/p/9964571.html