JSON 、python数据对象转换总结

1. JSON (JavaScript Object Notation) 是数据交换格式

json.dumps(): 对数据进行编码。---- 转储(dumps)为json字符串
json.loads(): 对数据进行解码。 ---- 加载(loads)为Python对象,如:列表;
dumps:无文件操作 dump:序列化+写入文件
loads:无文件操作 load: 读文件+反序列化
json模块和picle模块都有 dumps、dump、loads、load四种方法,而且用法一样
json模块序列化出来的是通用格式,其它编程语言都认识
picle模块序列化出来的只有python可以认识

json.dumps

#!/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 原始数据: {'url': 'http://www.runoob.com', 'no': 1, 'name': 'Runoob'}    
# JSON 对象: {"url": "http://www.runoob.com", "no": 1, "name": "Runoob"}


# 支持排序,缩进
>>> import json
>>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
{
    "4": 5,
    "6": 7
}

json.loads

#!/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

2. 字符串、列表、数组、字典、json转换

字符串转其他类型

# 字符串转其他类型
str1 = "This is a test!"
# 字符串 ---> 列表
print(list(str1))   #['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '!']
print(str1.split(" "))  #['This', 'is', 'a', 'test!']

# 字符串 ---> 元组
print(tuple(str1))  # ('T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '!')

# 字符串 ---> 集合
print(set(str1))   # {'t', 'e', '!', ' ', 'h', 'a', 'i', 's', 'T'}

# 字符串 ---> 字典
str2='{"name":"zhangsan","age":11}'
# fun1
print(eval(str2)) #{'name': 'zhangsan', 'age': 11}
# fun2
import json
print(json.loads(str2))  #{'name': 'zhangsan', 'age': 11}

猜你喜欢

转载自blog.csdn.net/hcj1101292065/article/details/94758517