python的json处理

"""
json中dumps、dump、loads、load 
这四个函数是经常用的,也是比较容易混淆的,给大家看一下这四个函数是怎么用的
"""

 1.json.dumps()函数是将其他类型的内容转化为字符串,用的最多的就是字典,当作入参用


dict_dict = {"name": "张三", "age": "12"}
dict_str = json.dumps(dict_dict, ensure_ascii=False)
print(type(dict_dict), dict_dict, '\n', type(dict_str), dict_str)

# 我们打印的时候就会看到,我的中文为什么乱码了,我们看一下dumps内容

# 这个是看源码中告诉我们的事情

If ``ensure_ascii`` is false, then the return value can contain non-ASCII characters if they appear in strings contained in ``obj``. Otherwise, all such characters are escaped in JSON strings.

# 有个参数是 ensure_ascii,如果这个参数是False,那么这些字符会原样输出,到json字符串中,如果是默认或者为True会保证输入的非ASCII字符转转译

 2、json.loads() 将一个json对象(str)转化为相对应的python对象,一般用来转换返回报文,然后获取相应报文节点下的数据

json_1 = '{"a":"1", "b":"1"}'
print(type(json_1), json_1)
json_2 = json.loads(json_1)
print(type(json_2), json_2)
3、json.dump():将python的对象转化为对应的json对象(str),并存放在文件中
json_msg = {"resultCode": 0,"data": {"zc": {"volumeUsed": "0.2","balanceHour": "","usedRate": 0,"lineName": "张三"}},"resultMessage": "成功"}
file = open('1.json', 'w')
json.dump(json_msg, file)
4、json.load():将一个存储在文件中的json对象(str)转化为相对应的python对象,两种方法都可以
# 方法1
file = open("1.json", 'r', encoding='utf-8')
info_load = json.load(file)
print(info_load)
# 方法2
with open('1.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    print('data%s'%data)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的json处理是指对JSON(JavaScript Object Notation)格式的数据进行解析和操作的过程。JSON是一种轻量级的数据交换格式,常用于前后端数据传输和存储。 在Python中,可以使用内置的json模块来进行json处理。该模块提供了一些函数和方法,可以将JSON数据转换为Python对象,或者将Python对象转换为JSON数据。 以下是Python处理JSON的一些常用方法和函数: 1. json.loads():将JSON字符串解析为Python对象。 2. json.dumps():将Python对象转换为JSON字符串。 3. json.load():从文件中读取JSON数据并解析为Python对象。 4. json.dump():将Python对象转换为JSON数据并写入文件。 5. json.loads()和json.dumps()还支持一些可选参数,如indent、sort_keys等,用于控制输出格式和排序方式。 示例代码如下: ```python import json # 将JSON字符串解析为Python对象 json_str = '{"name": "John", "age": 30, "city": "New York"}' data = json.loads(json_str) print(data["name"]) # 输出:John # 将Python对象转换为JSON字符串 data = {"name": "John", "age": 30, "city": "New York"} json_str = json.dumps(data) print(json_str) # 输出:{"name": "John", "age": 30, "city": "New York"} # 从文件中读取JSON数据并解析为Python对象 with open("data.json") as file: data = json.load(file) print(data["name"]) # 输出:John # 将Python对象转换为JSON数据并写入文件 data = {"name": "John", "age": 30, "city": "New York"} with open("data.json", "w") as file: json.dump(data, file) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值