Get the App
SLTechnology News&Howtos  ›  Development  › 

The method of conversion between object and json realized by python3

Shulou Source: shulou.com Published: 2022-06-03 06:01:09 10月10日 Update

The method of converting objects implemented by python3 into json. In view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Conversion operation between object and json implemented by python3

1. Python has three main data types: dictionary, list, and tuple, which are represented by curly braces, square brackets and parentheses respectively. For example:

Dictionary: dictData= {'aqiaqizuo 12 thecontrolling breadcracy 34}.

List: listData= [1, 2, 3, 4]

Tuple: tupleData= (1, 2, 3, 4)

two。 When using json, you can import import json.

3. Python object to json string, the main function used: json.dumps (). For example: example 1:

#! / usr/bin/env python3

#-*-coding: utf-8-*-

Import json

""

Convert python object to json string

""

# construct a dictionary

Python2json = {}

# construct list

ListTest = [1pm 2pm 3]

Python2json ["listTest"] = listTest

Python2json ["strData"] = "Python object to json."

# convert to json string

JsonStr = json.dumps (python2json)

Print (jsonstr)

Results:

{"listTest": [1,2,3], "strData": "Python object to json."} example 2:

#! / usr/bin/env python3

#-*-coding: utf-8-*-

Import json

""

Convert python object to json string

""

# construct a dictionary

Python2json = {}

# construct dict

DictData = {'adept: 123,' baked: [3, 4, 5], 'censor: (4, 5, 5)}

Python2json ["dictTest"] = dictData

# convert to json string

JsonStr = json.dumps (python2json)

Print (jsonStr)

Results:

{"dictTest": {"a": 123b ": [3,4,5]," c ": [4,5,6]}} the main function used to convert 4.json to python object is: json.loads (). For example:

#! / usr/bin/env python3

#-*-coding: utf-8-*-

Import json

""

Json to python object

""

Str ='{"Data1": [1,2,3], "Data2": "Json to python object."}'

Json2python = json.loads (str)

Print (json2python)

Results:

The format of {'Data1': [1,2,3],' Data2': 'Json to python object.'} 5.json encoding is almost the same as python syntax, except that True will be mapped to true,False, false,None will be mapped to null, and tuples () will be mapped to list [].

This is the answer to the question about the conversion between python3 objects and json. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Tags: Objects characters strings dictionaries methods results questions utf-8 functions parentheses more examples help solutions different easy consistent simple different different content Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Information Huawei Docker MySQL