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字符串,並寫入文件中javascript
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,對每一行分別作處理java
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