第二十一天学习:模块(三)json

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写
 
json 四种方法
json.loads
json.dumps
多s的用来处理字符串,没有s的处理文件
json.load
json.dump
 
load或loads 加载,把json格式转换成其他格式,字符串或文件相关的
dump或dumps 倾倒,将其他测试或对象转换成json字符串格式
https://www.json.cn/
 
(1)json类型与python数据的转换

import json

a = dict(name='xiaoming', age=18, message='hello world')
print(type(a), a)
b = json.dumps(a)
print(type(b), b)

c = json.loads(b)
print(type(c), c)
结果:
(<type 'dict'>, {'message': 'hello world', 'age': 18, 'name': 'xiaoming'})
(<type 'str'>, '{"message": "hello world", "age": 18, "name": "xiaoming"}')
(<type 'dict'>, {u'message': u'hello world', u'age': 18, u'name': u'xiaoming'})

  

(2)文件与json之间转换
load 从文件中加载数据,转换成json格式
dump 把json数据写入文件中
 

import json
jsondata = "{'a':1, 'b':2, 'c':3}"
with open('a.txt', 'w') as fd:
    json.dump(jsondata, fd)
with open('a.txt') as fd:
    ff = json.load(fd)
    print(ff)
    print(ff, type(ff))
结果:
{'a':1, 'b':2, 'c':3}
(u"{'a':1, 'b':2, 'c':3}", <type 'unicode'>)

  

posted @ 2017-11-14 00:12  男孩别哭  阅读(147)  评论(0编辑  收藏  举报