发布时间:2023-08-09 08:00
在Python中处理的是JSON字符串。JSON字符串必须用双引号括起来。
JSON的数据类型有很多,与Python互转存在一定的对应关系。
Python | JSON | JSON举例 |
---|---|---|
dict | object | {“employee”:{ “name”:“Bill Gates”, “age”:62, “city”:“Seattle” }} |
list,tuple | array, | [ “Bill”, “Steve”, “David” ] |
str | string | “Bill” |
int, long, float | number | 3.14 |
True | true | |
False | false | |
None | null |
#
import json
dict1 = {
\"name\": \"Bill\",
\"age\": 35,
\"married\": True,
\"children\": (\"Jennifer\", \"Rory\"),
\"car\": [\"Benz\", \"Audi\"]
}
print(dict1)
print(json.dumps(dict1))
print(\"-------------------\")
print(json.dumps(dict1, indent=4)) #按照4个空格的缩进进行格式化
print(type(json.dumps(dict1, indent=4)))
result:
# 可以看到在字典里,所有的字符串类型都是单引号。True首字母大写。
{\'name\': \'Bill\', \'age\': 35, \'married\': True, \'children\': (\'Jennifer\', \'Rory\'), \'car\': [\'Benz\', \'Audi\']}
{\"name\": \"Bill\", \"age\": 35, \"married\": true, \"children\": [\"Jennifer\", \"Rory\"], \"car\": [\"Benz\", \"Audi\"]}
-------------------
{
\"name\": \"Bill\",
\"age\": 35,
\"married\": true, # True变成了true
\"children\": [
\"Jennifer\",
\"Rory\"
],
\"car\": [
\"Benz\",
\"Audi\"
]
}
<class \'str\'> # 还是字符串,只不过print打印出来不带双引号,在命令行里可以看到带有双引号。
json.dumps([1, 2, 3])
result:
\'[1, 2, 3]\'
json.dumps(\'abc\')
result:
\'\"abc\"\'
json.dumps(True)
result:
\'true\'
# data.txt中内容:
# {\"name\": \"Bill\", \"married\": true, \"children\": [\"Jennifer\", \"Rory\"]}
import json
file_name = \"data.txt\"
msg = json.load(open(file_name))
print(type(msg), msg)
result:
<class \'dict\'> {\'name\': \'Bill\', \'married\': True, \'children\': [\'Jennifer\', \'Rory\']}
import json
data = \'{\"name\": \"Bill\", \"married\": true, \"children\": [\"Jennifer\", \"Rory\"]}\' # JSON字符串
msg = json.loads(data)
print(type(msg), msg)
result:
<class \'dict\'> {\'name\': \'Bill\', \'married\': True, \'children\': [\'Jennifer\', \'Rory\']}
import json
data = \'[\"a\", \"b\", 2, true]\'
msg = json.loads(data)
print(type(msg), msg)
result:
<class \'list\'> [\'a\', \'b\', 2, True]
import json
dict1 = {\'name\': \'Bill\', \'married\': True, \'children\': [\'Jennifer\', \'Rory\']}
js_str = json.dump(dict1, open(\"data.txt\", \"w\"), indent=4)
msg = json.load(open(\"data.txt\", \"r\")) #转换为Python对象
print(msg)
result:
{\'name\': \'Bill\', \'married\': True, \'children\': [\'Jennifer\', \'Rory\']}
import json
list1 = [1, 2, \"a\", True]
js_str = json.dumps(list1)
print(type(js_str), js_str)
result:
<class \'str\'> [1, 2, \"a\", true]
import json
dict1 = {\'name\': \'Bill\', \'married\': True, \'children\': [\'Jennifer\', \'Rory\']}
js_str = json.dumps(dict1, indent=4, separators=(\':: \', \'== \'))
print(type(js_str), js_str)
result:
<class \'str\'> {
\"name\"== \"Bill\"::
\"married\"== true::
\"children\"== [
\"Jennifer\"::
\"Rory\"
]
}