search

Python JSON

Nov 23, 2016 pm 01:51 PM

In this chapter we will introduce how to use Python language to encode and decode JSON objects.

Python 2.7 comes with JSON module [official document]

1. The conversion process from python original type to json type, the specific conversion is as follows:

import json

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.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)

python python json json

------------------------------------------------ --------

dict                                                                                                                                                                       ​at                                                                                                                                    null

>>> import json

>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])

'["foo ", {"bar": ["baz", null, 1.0, 2]}]'

>>> f = open('demo.txt','w')

>> ;> json.dump(range(100), f)

# Open demo.txt and you can see

[0, 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, 31, 32, 33, 34, 35 , 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 , 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85 , 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

2. The conversion process from json type to python, The specific conversion is as follows:

import json

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

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

                                                                                                                                                                        D Object Dict

Array List

String Str

Number (int) int

Number (Real) Float

True Trse False False

NULL NONE

GT; & GT; & GT; & GT; & GT; & GT; & GT; import json

>>> json.loads('{"a": 1, "b": 2, "c": 3}') # string to python objects

{u'a': 1, u' c': 3, u'b': 2}

# Contents in 1.txt

[{"a": [1, 2, 3, 4, 5]}, {"b" : [1, 2, 3]}, {"c": ["English", "Chinese"]}]

>>> f = open('1.txt')

> >> json.load(f)

[{u'a': [1, 2, 3, 4, 5]}, {u'b': [1, 2, 3]}, {u' c': [u'English', u'Chinese']}]

Old version of Python environment configuration (users who come with the json module in Python do not need to look at it)

Using Python to encode or decode JSON Before data, we need to install the JSON module first. In this tutorial we will download Demjson and install it:

$tar

JSON function

Function

Description

encode Encode a Python object into a JSON string

decode Decode an encoded JSON string into a Python object

encode

Python encode() Function for encoding Python objects into JSON strings.

Syntax

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

Example

The following example encodes an array into JSON format data:

#! /usr/bin/python

import demjson

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

json = demjson.encode(data)

print json

The execution result of the above code is:

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

decode

Python can use the demjson.decode() function to decode JSON data. This function returns the data type of the Python field.

Syntax

demjson.decode(self, txt)

Example

The following example shows how Python decodes JSON objects:

#!/usr/bin /python

import demjson

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

text = demjson.decode(json)

print text

The above code execution result is:

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

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
What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

What are unit tests in Python?What are unit tests in Python?Apr 30, 2025 pm 02:05 PM

The article discusses unit tests in Python, their benefits, and how to write them effectively. It highlights tools like unittest and pytest for testing.

What are Access Specifiers in Python?What are Access Specifiers in Python?Apr 30, 2025 pm 02:03 PM

Article discusses access specifiers in Python, which use naming conventions to indicate visibility of class members, rather than strict enforcement.

What is __init__() in Python and how does self play a role in it?What is __init__() in Python and how does self play a role in it?Apr 30, 2025 pm 02:02 PM

Article discusses Python's \_\_init\_\_() method and self's role in initializing object attributes. Other class methods and inheritance's impact on \_\_init\_\_() are also covered.

What is the difference between @classmethod, @staticmethod and instance methods in Python?What is the difference between @classmethod, @staticmethod and instance methods in Python?Apr 30, 2025 pm 02:01 PM

The article discusses the differences between @classmethod, @staticmethod, and instance methods in Python, detailing their properties, use cases, and benefits. It explains how to choose the right method type based on the required functionality and da

How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools