python内置模块(json)

1、Json简介:
Json,全名 JavaScript Object Notation,是一种轻量级的数据交换格式。Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式。现在也常用于http请求中,所以对json的各种学习,是自然而然的事情。

2、json类型和python数据的转换

import json
# 例子1
a = dict(name = 'andyfeng', age = 20, message = 'hello')
print(a)
print(type(a))
b = json.dumps(a)
print(b)
print(type(b))

结果如下:

{'message': 'hello', 'age': 20, 'name': 'andyfeng'}
<type 'dict'>
{"message": "hello", "age": 20, "name": "andyfeng"}
<type 'str'>

可以通过www.json.cn对json转换内容进行解析

{"message": "hello", "age": 20, "name": "andyfeng"}

解析后

{
    "message":"hello",
    "age":20,
    "name":"andyfeng"
}

3、json.loads()将json字符串解码成python对象。
在工作中,很多情况是别人给你提供的接口就是json字符串形式的。比如:你在数据库中查到的数据,返回结果是一个json的字符串的形式,这你就需要自己把这些json字符串转换成json对象。

import json
# 例子1
a = dict(name = 'andyfeng', age = 20, message = 'hello')
print(a)
print(type(a))
b = json.dumps(a)
print(b)
print(type(b))

# 例子2
print('@@@@@@@@@@@@@@')#标记用
c = json.loads(b)
print(type(c))
print(c)

结果如下:

{'message': 'hello', 'age': 20, 'name': 'andyfeng'}
<type 'dict'>
{"message": "hello", "age": 20, "name": "andyfeng"}
<type 'str'>
@@@@@@@@@@@@@@
<type 'dict'>
{u'message': u'hello', u'age': 20, u'name': u'andyfeng'}

说明:
通过json.loads方法把json字符串转换成python的数据字典。

4、文件和json之间的转换

#文件相关
# load肯定是从文件中逃出来json数据,load肯定是把文件转换成json数据
#dump 就是把json数据写入到文件中
# 把json写入文件中 dump
jsondata = '{"a":1, "b":2, "c":3, "d":4, "e":5}'#外面可以用单引号‘’或三个单引号‘‘‘ ’’’
with open('a.txt', 'w')as f:
    json.dump(jsondata, f)

结果截图:
这里写图片描述

说明:
json.dump()可以把json数据直接写入到文件中。

5、json.load()

#文件相关
# load肯定是从文件中逃出来json数据,load肯定是把文件转换成json数据
#dump 就是把json数据写入到文件中
# 把json写入文件中 dump
jsondata = '{"a":1, "b":2, "c":3, "d":4, "e":5}'#外面可以用单引号‘’或三个单引号‘‘‘ ’’’
with open('a.txt', 'w')as f:
    json.dump(jsondata, f)

with open('a.txt', 'r') as fr:
    m = json.load(fr)
    print(m)
    print(type(m))

结果:

{"a":1, "b":2, "c":3, "d":4, "e":5}
<type 'unicode'>

Process finished with exit code 0

说明:
json.load()把文件内容转换成unicode数据类型返回

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值