JSON是一种比轻量级的数据交换格式。比XML更小、更快、更容易解析。

JSON语法时JavaScript对象表示语法的子集。书写格式为:键:值。用英文逗号为分隔符,{}大括号报错对象,[]中括号报错数组。

python3中使用json模块对JSON进行编码和解码,通常包括以下两个函数:

json.drumps() 对数据进行编码

json.loads() 对数据进行解码

python 解析json数组 python 解析 json_Python

在编码过程中,python原始类型和JSON类型相互转换。

python编码为JSON类型转换对应表:

Python

JSON

dict

object

list, tuple

array

str

string

int, float, int- & float-derived Enums

number

True

true

False

false

None

null

JSON解码为python类型转换对应表:

JSON

Python

object

dict

array

list

string

str

number (int)

int

number (real)

float

true

True

false

False

null

None

 

实例1 python编码为JSON类型:

#!/usr/bin/python3
 
import json
 
# Python 字典类型转换为 JSON 对象
data = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}
 
json_str = json.dumps(data)
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)

输出:

Python 原始数据: {'no': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
JSON 对象: {"no": 1, "name": "Runoob", "url": "http://www.runoob.com"}

实例2 JSON解码为python类型:

#!/usr/bin/python3
 
import json
 
# Python 字典类型转换为 JSON 对象
data1 = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}
 
json_str = json.dumps(data1)
print ("Python 原始数据:", repr(data1))
print ("JSON 对象:", json_str)
 
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])

 输出:

Python 原始数据: {'no': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
JSON 对象: {"no": 1, "name": "Runoob", "url": "http://www.runoob.com"}
data2['name']:  Runoob
data2['url']:  http://www.runoob.com