json是存储和交换文本信息的语法,和XML类似
json比xml更小,更快,更容易解析
json实例:
{
"shidong": [
{ "name":"百度" , "url":"www.baidu.com" },
{ "name":"google" , "url":"www.google.com" },
{ "name":"微博" , "url":"www.weibo.com" }
]
}
"shidong": [
{ "name":"百度" , "url":"www.baidu.com" },
{ "name":"google" , "url":"www.google.com" },
{ "name":"微博" , "url":"www.weibo.com" }
]
}
sites对象包含了三个对象
json指的是JavaScript对象表示法
json是轻量级的文本数据交换格式
#!/usr/bin/env python
# encoding: utf-8
import json
from pprint import pprint
info_string = """{
"name":"shidong",
"age":24,
"coding skills":["python","matlab","java","c","c++","Ruby","shell"],
"ages for school":{
"primary school":6,
"middle school":9,
"high school":15
},
"hobby":["sports","reading"],
"married":false
}
"""
info = json.loads(info_string)#利用json.loads()方法从字符串中读取json数据
pprint(info)
print(type(info))
#也可以使用json.dumps()将一个Python对象编程Json对象:
# info_json = json.dumps(info)
# print(info_json)
# print(type(info_json))
#把对象保存为json文件
with open("info.json","w") as f:
json.dump(info,f)
#查看info.json的内容
with open("info.json") as f:
print(f.read())
#从文件中读取数据
with open("test.json") as f:
info_from_file = json.load(f) #jsoan.load()从文件中读取数据
pprint(info_from_file)