Python中json模块的使用

12 篇文章 1 订阅

一.python2

1.序列化

1.1 将字典转化为字符串

json.dumps()
import json

dict_json = {'a': 123, 'b': 456, 'c': 'pen'}

print json.dumps(dict_json)
{"a": 123, "c": "pen", "b": 456}

1.2 将字典转为格式化后的字符串

json.dumps(dict, indent=2, separators=(',', ':'))

indent: 缩进位数

separators: 元素间以逗号分隔, key-value间以冒号分隔

import json

dict_json = {"a": 1, "b": {"list": [1, 2, 3], "str": "hello"}, "c": 3}

format_json = json.dumps(dict_json, indent=4, separators=(',', ':'))

print format_json
{
    "a":1,
    "c":3,
    "b":{
        "list":[
            1,
            2,
            3
        ],
        "str":"hello"
    }
}

 1.3 将字典写进文件

json.dump(json_dict, file_object)
import json

json_dict = {"a": 123, "b": 456, "c": "pen"}

file_object = open('why.json', 'w')

json.dump(json_dict, file_object)

2.反序列化

2.1 将字符串转为字典

json.loads()
import json

dict_str = '{"a": 123, "b": 456, "c": "pen"}'

print json.loads(dict_str)
{u'a': 123, u'c': u'pen', u'b': 456}

2.2 读取文件中的数据并转为字典

json.load(file_object)
import json

file_object = open('why.json', 'r')

info = json.load(file_object)

print(info)

print type(info)
{u'a': 123, u'c': u'pen', u'b': 456}
<type 'dict'>

二.python3:

1.序列化

1.1 将字典转化为字符串

json.dumps(dict_json, ensure_ascii=False)

 ensure_ascii=False 解决中文乱码

import json

dict_json = {"a": 1, "b": {"list": [1, 2, 3], "str": "测试"}, "c": 3}

format_json = json.dumps(dict_json, ensure_ascii=False)

print(format_json)
{"a": 1, "b": {"list": [1, 2, 3], "str": "测试"}, "c": 3}

1.2 将字典转为格式化后的字符串

json.dumps(dict_json, indent=4, separators=(',', ':'), ensure_ascii=False)
import json

dict_json = {"a": 1, "b": {"list": [1, 2, 3], "str": "测试"}, "c": 3}

format_json = json.dumps(dict_json, indent=4, separators=(',', ':'), ensure_ascii=False)

print(format_json)
{
    "a":1,
    "b":{
        "list":[
            1,
            2,
            3
        ],
        "str":"测试"
    },
    "c":3
}

 1.3 将字典写进文件

json.dump(json_dict, file_object, ensure_ascii=False)
import json

json_dict = {"a": 123, "b": 456, "c": "测试"}

file_object = open('why.json', 'w', encoding="utf8")

json.dump(json_dict, file_object, ensure_ascii=False)

2.反序列化

2.1 将字符串转为字典

json.loads(dict_str)
import json

dict_str = '{"a": 123, "b": 456, "c": "测试"}'

print(json.loads(dict_str))
{'a': 123, 'b': 456, 'c': '测试'}

2.2 读取文件中的数据并转为字典

json.load(file_object)
import json

file_object = open('why.json', 'r', encoding="utf8")

info = json.load(file_object)

print(info)
{'a': 123, 'b': 456, 'c': '测试'}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纯洁的小魔鬼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值