search
HomeBackend DevelopmentPython TutorialPython json模块使用实例

实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接传递,所以需要将其转换成字符串形式.转换的过程也是一种序列化过程.

用json.dumps序列化为json字符串格式

复制代码 代码如下:

>>> import json
>>> dic {'Connection': ['keep-alive'], 'Host': ['127.0.0.1:5000'], 'Cache-Control': ['max-age=0']}
>>> jdict = json.dumps({'Connection': ['keep-alive'], 'Host': ['127.0.0.1:5000'], 'Cache-Control': ['max-age=0']})
>>> print jdict
{"Connection": ["keep-alive"], "Host": ["127.0.0.1:5000"], "Cache-Control": ["max-age=0"]}

虽然dic和jdict打印的字符串是相同的,但是实际它们的类型是不一样的.dic是字典类型,jdict是字符串类型
复制代码 代码如下:


>>> type(jdic)
>>> type(jdict)


可以用json.dumps序列化列表为json字符串格式
复制代码 代码如下:

>>> list = [1, 4, 3, 2, 5]
>>> jlist = json.dumps(list)
>>> print jlist
[1, 4, 3, 2, 5]

list和jlist类型同样是不一样的
复制代码 代码如下:

>>> type(list)

>>> type(jlist)

json.dumps有如下多种参数

复制代码 代码如下:

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)

key排序
复制代码 代码如下:

>>> print json.dumps({1:'a', 4:'b', 3:'c', 2:'d', 5:'f'},sort_keys=True)
{"1": "a", "2": "d", "3": "c", "4": "b", "5": "f"}

格式对齐

复制代码 代码如下:

>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
    "4": 5,
    "6": 7
}

指定分隔符
复制代码 代码如下:

>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'

用json.dump序列化到文件对象中
复制代码 代码如下:

>>> json.dump({'4': 5, '6': 7}, open('savejson.txt', 'w'))
>>> print open('savejson.txt').readlines()
['{"4": 5, "6": 7}']

json.dump参数和json.dumps类似

复制代码 代码如下:

json.dump(obj, fp, 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.loads把json字符串反序列化为python对象

函数签名为:

复制代码 代码如下:

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

注意这里的”s”必须是字符串,反序列化后为unicode字符
复制代码 代码如下:

>>> dobj = json.loads('{"name":"aaa", "age":18}')
>>> type(dobj)

>>> print dobj
{u'age': 18, u'name': u'aaa'}

json.load从文件中反序列化为python对象

签名为:

复制代码 代码如下:

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

实例:
复制代码 代码如下:

>>> fobj = json.load(open('savejson.txt'))
>>> print fobj
{u'4': 5, u'6': 7}
>>> type(fobj)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

How does the memory footprint of a list compare to the memory footprint of an array in Python?How does the memory footprint of a list compare to the memory footprint of an array in Python?May 02, 2025 am 12:08 AM

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

How do you handle environment-specific configurations when deploying executable Python scripts?How do you handle environment-specific configurations when deploying executable Python scripts?May 02, 2025 am 12:07 AM

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools