記事のディレクトリ
1. JSON(JavaScript Object Notation)は、データ交換フォーマットであります
json.dumps():データを符号化します。JSON文字列の----ダンプ(ダンプ)
json.loads():データを復号します。以下のようなPythonオブジェクトに変換する----ロード(負荷):リスト;
ダンプ:なしダンプ・ファイル操作:+シリアル化されたファイルの書かれた
負荷を:いいえ、ファイル操作の負荷を:ファイル+デシリアライズ読む
JSONモジュールを、モジュールがpicleダンプを持っています、の使用のようなダンプ、ロード、負荷4つの方法、及び、
共通フォーマットのうちJSONシリアライズモジュール、他のプログラミング言語を知っている
のpythonのうち、picle直列化モジュールのみを認識することができ
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}