小猿圈python之json学习

首先,我们得了解,JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。使用 JSON 函数需要导入 json 库:import json,那么json具体应该怎么用呢,它有什么作用呢?小猿圈加加这篇文章详解一下,感兴趣的朋友可以看一下。

函数                                 描述

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

json.loads 将已编码的 JSON 字符串解码为 Python 对象

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)

以下为实例:

#!/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': 'luyaran', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))

{

    "a": "luyaran",

    "b": 7

}

    我们来看python 原始类型向 json 类型的转化对照表:

Python               JSON

dict               object

list, tuple               array

str, unicode            string

int, long, float number

True                 true

False                 false

None                   null

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 的类型对照表:

JSON                   Python

object                   dict

array                     list

string                   unicode

number (int)     int, long

number (real)     float

true                     True

false                     False

null                     None

在使用 Demjson 编码或解码 JSON 数据前,我们需要先安装 Demjson 模块:

$ tar -xvzf demjson-2.2.3.tar.gz

$ cd demjson-2.2.3

$ python setup.py install

看下json函数表单:

函数                                               描述

encode                       将 Python 对象编码成 JSON 字符串

decode                       将已编码的 JSON 字符串解码为 Python 对象

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}]

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}

文章写到这里就完事了,相信大家看完文章后对json在python中使用有所了解了,json的编码转换在实际项目中有很大用处,希望大家可以在小的项目中练习一下,这样更容易学透彻,想要看更文章,可以关注一下小猿圈加加哦,每天更新!

猜你喜欢

转载自blog.csdn.net/qq_42210792/article/details/95329492