JSON ==> Javascript Object Notation
AJAX 就是一种 key:value 的形式
json有四种方法:
json.loads
json.dumps
理解:加s的是用来处理字符串的
json.load
json.dump
理解:不加s的是用来处理文件的
load 或者 loads
意思:把json转换成其他对象,字符串或者文件相关的。
dump 或者 dumps
意思:把其他对象或者格式,转换成json格式
1.字符串和json之间的转换
举例1:把python字典的格式转换成json字符串格式
1
2
3
4
5
6
7
8
9
10
11
|
>>> a
=
dict
(name
=
'linan'
,age
=
'22'
,message
=
'yes'
)
>>>
print
a
{
'message'
:
'yes'
,
'age'
:
'22'
,
'name'
:
'linan'
}
>>>
print
type
(a)
<
type
'dict'
>
>>>
import
json
>>> b
=
json.dumps(a)
>>>
print
b
{
"message"
:
"yes"
,
"age"
:
"22"
,
"name"
:
"linan"
}
>>>
print
type
(b)
<
type
'str'
>
|
print a 和 print b 虽然一样,但是格式已经改变
https://www.json.cn/ 这个网站支持json解析
举例2:将字符串转换成字典
1
2
3
4
5
|
>>> c
=
json.loads(b)
>>>
print
c
{u
'message'
: u
'yes'
, u
'age'
: u
'22'
, u
'name'
: u
'linan'
}
>>>
print
type
(c)
<
type
'dict'
>
|
2.文件和json之间的转换
load 肯定是从文件中搞出来json数据,转换成json数据
dump 就是把json数据写入到文件中
将字符串转换成json格式写入到文件中
1
2
3
4
|
import
json
jsonData
=
'''{"a":1,"b":2,"c":3,"d":4,"e":5}'''
##字符串文件内写成三引号或者单引号
with
open
(
'a.txt'
,
'w'
) as f:
json.dump(jsonData, f)
|
结果
a.txt 文件内容如下:
"{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}"
所以,json.dump()可以将json数据直接写入到文件中。
将json格式的文件内容转换成字符串
1
2
3
4
|
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'>
所以,json.load()吧文件内容转换成unicode数据类型返回
本文转自 听丶飞鸟说 51CTO博客,原文链接:http://blog.51cto.com/286577399/1981382