【Python】json编码和解码器

json编码和解码

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数:

  • json.dumps(): 对数据进行编码。
  • json.loads(): 对数据进行解码。

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

函数原型:

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, \
           allow_nan=True, cls=None, indent=None, separators=None, default=None, \
           sort_keys=False, **kw)

 

1. 例1:

import json
print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')))
print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ': ')))
print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(', ', ': ')))
print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], indent=2, separators=(', ', ': ')))
print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], indent=4, separators=(', ', ': ')))

输出:

[1,2,3,{"4":5,"6":7}]
[1,2,3,{"4": 5,"6": 7}]
[1, 2, 3, {"4": 5, "6": 7}]
[
  1, 
  2, 
  3, 
  {
    "4": 5, 
    "6": 7
  }
]
[
    1, 
    2, 
    3, 
    {
        "4": 5, 
        "6": 7
    }
]
import json
 
# Python 字典类型转换为 JSON 对象
data1 = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}
 
json_str01 = json.dumps(data1)
json_str02 = json.dumps(data1,  indent=4)
print ("Python 原始数据:", repr(data1))
print ("JSON 对象:", json_str01)
print ("JSON 对象:", json_str02)
 
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str01)
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"}
JSON 对象: {
    "no": 1,
    "name": "Runoob",
    "url": "http://www.runoob.com"
}
data2['name']:  Runoob
data2['url']:  http://www.runoob.com

 

函数原型:

json.loads(s, *, cls=None, object_hook=None, parse_float=None, \
           parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

 

文件名为data.json:

# importing the module
import json
 
# Opening JSON file
with open('data.json') as json_file:
    data = json.load(json_file)
 
    # Print the type of data variable
    print("Type:", type(data))
 
    # Print the data of dictionary
    print("\nPeople1:", data['people1'])
    print("\nPeople2:", data['people2'])

输出:

 

# importing the module
import json
 
# Opening JSON file
with open('data.json') as json_file:
    data = json.load(json_file)
 
    # for reading nested data [0] represents
    # the index value of the list
    print(data['people1'][0])
     
    # for printing the key-value pair of
    # nested dictionary for loop can be used
    print("\nPrinting nested dictionary as a key-value pair\n")
    for i in data['people1']:
        print("Name:", i['name'])
        print("Website:", i['website'])
        print("From:", i['from'])
        print()

输出:

 

# Python program to read
# json file

import json

# Opening JSON file
f = open('data.json')

# returns JSON object as
# a dictionary
data = json.load(f)

# Iterating through the json
# list
for i in data['emp_details']:
	print(i)

# Closing file
f.close()

 

参考资料

1. json编码和解码

posted @ 2018-05-21 15:52  苏格拉底的落泪  阅读(176)  评论(0编辑  收藏  举报