JSON, python object conversion data summary

1. JSON (JavaScript Object Notation) is a data exchange format

json.dumps (): encode the data. ---- dump (dumps) of json string
json.loads (): decodes the data. ---- load (loads) into Python objects, such as: a list;
dumps: None the dump file operations: + serialized file written
loads: No file operation load: Read File + deserialization
json module and the module has picle dumps , dump, loads, load four methods, and, like the use of
json serialization module out of the common format, other programming languages know
picle serialization module out of the python can only recognize

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. strings, lists, arrays, dictionaries, json conversion

Other types of string transfer

# 字符串转其他类型
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}

Guess you like

Origin blog.csdn.net/hcj1101292065/article/details/94758517