python ----json数据处理

1、什么是JSON:

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。第一次接触到它是在进行服务器端接口测试的时候。现在很多服务器返回的结果都是json格式。主要是由于它比较容易解析和生成。JSON格式的数据本质上一种被格式化了的字符串。

2、Python处理JSON

用Python处理json也很简单,Python自带有json模块。可以对python对象与json字符串进行相互转换。

2.1、编码

json.dumps()把一个Python对象编,码转换成Json字符串。
举个例子:

>>> import json
>>> python_obj = [[1,2,3],123,123.123,'abc',{'key1':(1,2,3),'key2':(4,5,6)},True,False,None]
>>> json_str=json.dumps(python_obj)
>>> print json_str
[[1, 2, 3], 123, 123.123, "abc", {"key2": [4, 5, 6], "key1": [1, 2, 3]}, true, false, null]
  • 1
  • 2
  • 3
  • 4
  • 5

通过输出的结果可以看出,简单类型的python对象通过encode之后跟其原始的repr()输出结果非常相似,但是有些数据类型进行了改变,例如上例中的元组则转换为了列表,True变成了true,Flase变成了false,None变成了null。也就是说在json的编码过程中,会存在从python原始类型向json类型的转化过程。具体的转化对照如下:
这里写图片描述
json.dumps方法提供了很多好用的参数可供选择,比较常用的有sort_keys(对dict对象进行排序,我们知道默认dict是无序存放的),skipkeys(对于键不是基本类型Python字典键值对将被过滤),indent(格式化输出用的)等参数。还是举个例子:

>> python_obj2={"key2": [4, 5, 6], "key1": [1, 2, 3]}
>>> json_str2=json.dumps(python_obj2)
>>> json_str2=json.dumps(python_obj2,sort_keys=True,indent=2)
>>> print json_str2
{
  "key1": [
    1, 
    2, 
    3
  ], 
  "key2": [
    4, 
    5, 
    6
  ]
}
>>> json_str2=json.dumps(python_obj2,sort_keys=False,indent=2)
>>> print json_str2
{
  "key2": [
    4, 
    5, 
    6
  ], 
  "key1": [
    1, 
    2, 
    3
  ]
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

sort_keys=True时,压缩过后的json字符串中字典是被排过序的。再加上indent的参数进行适当的缩进,打印此来的json字符串很漂亮。

2.2、解码

json.loads()把Json格式字符串解码,转换成Python对象。
还是举个例子,将上例中编码的json字符串再解码成Python对象:

>>> print json.loads(json_str)
[[1, 2, 3], 123, 123.123, u'abc', {u'key2': [4, 5, 6], u'key1': [1, 2, 3]}, True, False, None]
  • 1
  • 2

loads方法返回了原始的对象,但是仍然发生了一些数据类型的转化。比如,上例中‘abc’转化为了unicode类型。从json到python的类型转化对照如下:
这里写图片描述

===========================================================================================================================

如何使用 Python 语言来编码和解码 JSON 对象。

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。


JSON 函数

使用 JSON 函数需要导入 json 库:import json

函数描述
json.dumps 将 Python 对象编码成 JSON 字符串
json.loads 将已编码的 JSON 字符串解码为 Python 对象

json.dumps

json.dumps 用于将 Python 对象编码成 JSON 字符串。

语法

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)

实例

以下实例将数组编码为 JSON 格式数据:

#!/usr/bin/python
import json

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]

json = json.dumps(data)
print json

以上代码执行结果为:

[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]

使用参数让 JSON 数据格式化输出:

>>> import json
>>> print json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
{
    "a": "Runoob",
    "b": 7
}

python 原始类型向 json 类型的转化对照表:

PythonJSON
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None null

json.loads

json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。

语法

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

实例

以下实例展示了Python 如何解码 JSON 对象:

#!/usr/bin/python
import json

jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

text = json.loads(jsonData)
print text

以上代码执行结果为:

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}

json 类型转换到 python 的类型对照表:

JSONPython
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None

使用第三方库:Demjson

Demjson 是 python 的第三方模块库,可用于编码和解码 JSON 数据,包含了 JSONLint 的格式化及校验功能。

Github 地址:https://github.com/dmeranda/demjson

官方地址:http://deron.meranda.us/python/demjson/

环境配置

在使用 Demjson 编码或解码 JSON 数据前,我们需要先安装 Demjson 模块。本教程我们会下载 Demjson 并安装:

$ tar -xvzf demjson-2.2.3.tar.gz
$ cd demjson-2.2.3
$ python setup.py install

更多安装介绍查看:http://deron.meranda.us/python/demjson/install

JSON 函数

函数描述
encode 将 Python 对象编码成 JSON 字符串
decode 将已编码的 JSON 字符串解码为 Python 对象

encode

Python encode() 函数用于将 Python 对象编码成 JSON 字符串。

语法

demjson.encode(self, obj, nest_level=0)

实例

以下实例将数组编码为 JSON 格式数据:

#!/usr/bin/python
import demjson

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]

json = demjson.encode(data)
print json

以上代码执行结果为:

[{"a":1,"b":2,"c":3,"d":4,"e":5}]

decode

Python 可以使用 demjson.decode() 函数解码 JSON 数据。该函数返回 Python 字段的数据类型。

语法

demjson.decode(self, txt)

实例

以下实例展示了Python 如何解码 JSON 对象:

#!/usr/bin/python
import demjson

json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

text = demjson.decode(json)
print  text

以上代码执行结果为:

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
原文地址:https://www.cnblogs.com/dpf-learn/p/8011324.html