作者 | 猪哥
责编 | maozz
{
"person": {
"name":
"pig",
"age":
"18",
"sex":
"man",
"hometown": {
"province":
"江西省",
"city":
"抚州市",
"county":
"崇仁县"
}
}
}
[
"pig",
18,
"man",
"江西省抚州市崇仁县"]
{
"code":
1,
"msg":
"success",
"data": {
"name":
"pig",
"age":
"18",
"sex":
"man",
"hometown": {
"province":
"江西省",
"city":
"抚州市",
"county":
"崇仁县"
}
}
}
{
"name":
"server",
//项目名称
"version":
"0.0.0",
"private":
true,
"main":
"server.js",
//项目入口地址,即执行npm后会执行的项目
"scripts": {
"start":
"node ./bin/www"
///scripts指定了运行脚本命令的npm命令行缩写
},
"dependencies": {
"cookie-parser":
"~1.4.3",
//指定项目开发所需的模块
"debug":
"~2.6.9",
"express":
"~4.16.0",
"http-errors":
"~1.6.2",
"jade":
"~1.11.0",
"morgan":
"~1.9.0"
}
}
import json
# 1、Python的dict类型转JSON
person_dict = {
'name':
'pig',
'age':
18,
'sex':
'man',
'hometown':
'江西抚州'}
# indent参数为缩进空格数
person_dict_json = json.dumps(person_dict, indent=
4)
print(person_dict_json,
'\n')
# 2、Python的列表类型转JSON
person_list = [
'pig',
18,
'man',
'江西抚州']
person_list_json = json.dumps(person_list)
print(person_list_json,
'\n')
# 3、Python的对象类型转JSON
person_obj = Person(
'pig',
18,
'man',
'江西抚州')
# 中间的匿名函数是获得对象所有属性的字典形式
person_obj_json = json.dumps(person_obj,
default=lambda obj: obj.__dict__, indent=
4)
print(person_obj_json,
'\n')
# 4、JSON转Python的dict类型
person_json = '{
"name":
"pig",
"age": 18,
"sex":
"man",
"hometown":
"江西抚州"}'
person_json_dict = json.loads(person_json)
print(type(person_json_dict), '\n')
# 5、JSON转Python的列表类型
person_json2 = '[
"pig", 18,
"man",
"江西抚州"]'
person_json_list = json.loads(person_json2)
print(type(person_json_list), '\n')
# 6、JSON转Python的自定义对象类型
person_json = '{
"name":
"pig",
"age": 18,
"sex":
"man",
"hometown":
"江西抚州"}'
# object_hook参数是将dict对象转成自定义对象
person_json_obj = json.loads(person_json, object_hook=lambda d: Person(d['name'], d['age'], d['sex'], d['hometown']))
print(type(person_json_obj), '\n')
\u6c5f\u897f\u629a\u5dde
热 文 推 荐