- JSON是以人类更易读的方式传输结构化数据。
- JSON不使用单引号,每个字符串都使用双引号分隔。
- JSON与Python的转换示例代码如下:
# encoding: utf-8
import json
books = {
'0132269937': {
'title': 'Core Python Programming',
'edition': 2,
'year': 2007,
},
'0132356139': {
'title': 'Python Web Development with Django',
'authors': ['Jeff Forcier', 'Paul Bissex', 'Wesley Chun'],
'year':2009,
},
}
# 字典dumps成JSON
json_str = json.dumps(books,ensure_ascii=False)
print(json_str)
# {"0132269937": {"title": "Core Python Programming", "edition": 2, "year": 2007}, "0132356139": {"title": "Python
# Web Development with Django", "authors": ["Jeff Forcier", "Paul Bissex", "Wesley Chun"], "year": 2009}}
print(type(json_str))
# <class 'str'>
# 字典dump到文件中
with open('js.json','w') as fp:
json.dump(books,fp)
# 将json字符串loads成python对象
book_py = json.loads(json_str, encoding='utf-8')
print(book_py)
# {'0132269937': {'title': 'Core Python Programming', 'edition': 2, 'year': 2007}, '0132356139': {'title': 'Python Web Development with Django', 'authors': ['Jeff Forcier', 'Paul Bissex', 'Wesley Chun'], 'year': 2009}}
print(type(book_py))
# <class 'dict'>
# 在文件中读取json
with open ('js.json','r') as fp:
js_str = json.load(fp)
print(js_str)