Json data and Python type conversion

Json packet

This section focuses on converting JSON data to Python data.

Json objects and Python dictionaries are converted using the built-in JSON package, which is described in detail below. Detailed learning material see’s official website: https://docs.python.org/3/library/json.html

Import the package directly when first used:

import json

Copy the code

The JSON package contains four methods for converting to Python’s built-in data types:

methods role
json.dumps() Encode python objects as Json strings:The dictionary to json
json.loads() Decode Json strings into Python objects:Json to the dictionary
json.dump() Convert objects in Python to JSON and store them in a file
json.load() Extract the JSON format from the file into a Python object

Note: The two load-related methods just add one more step to the file-related operations.

json.dumps

Dump is used to convert Python data types to JSON.

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

The json.dumps method converts Python dictionary data into JSON data with the following parameters:

json.dumps(obj,   The object to be converted

           skipkeys=False.# the default value is False, if the data is not within the keys of dict python's basic types (STR, unicode, int, long, float, Boolean, None), set to False, will offer the wrong TypeError. If set to True, this type of key will be skipped

           ensure_ascii=True.The default value is ASCII. If set to False, Chinese characters can be printed

           check_circular=True.If False, skip checking for circular references to container types

           allow_nan=True.# If allow_nan is false, ValueError will serialize out-of-range floating point values (nan, INF, -INF), strictly following JSON specifications, instead of using JavaScript values (nan, Infinity, -infinity)

           cls=None.

           indent=None.The # parameter is indented according to the format, indicating a few Spaces

           separators=None.# specify a delimiter; Contains delimiters between dict items and between key and value; Also remove ':'

           encoding="utf-8".# code

           default=None.The default is a function that should return a serializable version of obJ or throw a type error; The default is to raise only type errors

           sort_keys=False.If False, the dictionary keys are not sorted; Set to True, sort by dictionary (a to Z)

           **kw)

Copy the code

Use examples to illustrate the above common parameters

1. When Chinese is present in our Python-type data

information1 = {

    'name''Ming'.

    'age'18.

    'address''shenzhen'

}

# dictionary is converted to JSON data

information2 = json.dumps(information1)



print(type(information1))

print(type(information2))

print(information2)

Copy the code

Add ensure_ASCII =False to display:

# dictionary is converted to JSON data

information3 = json.dumps(information1,ensure_ascii=False)

Copy the code

⚠️ The result shows that all json data is changed to double quotation marks. The original dictionary data used single quotation marks. Let’s look at another example about quotation marks:

>>>import json

>>>print(json.dumps({'4'5.'6'7}, sort_keys=True, indent=4))  Keys in # Python are strings, in single quotes



# result display

{

    "4"5.# becomes double quotation marks

    "6"7

}

Copy the code

2. Output json data with indent and indent parameters

information4 = {

    'name''Ming'.

    'age'18.

    'skills''python'.

    'english''CET6'.

    'major''accounting'.

    'address''shenzhen'

}



information5 = json.dumps(information4, ensure_ascii=False)   # don't indent

information6 = json.dumps(information4, ensure_ascii=False, indent=2)  # Indent 2 Spaces

information7 = json.dumps(information4, ensure_ascii=False, indent=5)  Indent 5 Spaces





print(information5)

print(information6)

print(information7)

Copy the code

3. Sort the output of keys in Python data types

information4 = {

    'name''Ming'.

    'age'18.

    'skills''python'.

    'english''CET6'.

    'major''accounting'.

    'address''shenzhen'

}



information8 = json.dumps(information4, ensure_ascii=False, indent=2)  #

information9 = json.dumps(information4, ensure_ascii=False, indent=2,sort_keys=True)  # key sort set to True



print(information8)

print(information9)

Copy the code

With sort_keys=True, you can see that the output results are sorted by initial letters. When the first letter is the same, sort by the second letter.

4. Control of output delimiters

Use the separators parameter to set different output separators. The default between dic elements is, and the default between key-value pairs is:

information1 = {

    'name''Ming'.

    'age'18.

    'address''shenzhen'

}



information2 = json.dumps(information1,ensure_ascii=False)

information10 = json.dumps(information1,ensure_ascii=False,separators=('+'.The '@'))  # change the separator



print(information2)  # default connecter

print(information10)  

Copy the code

json.dump

Json.dump is similar to json.dumps except that the data is stored in a file. The parameters are the same

We tried to write the following personal information to the file

information = {

    'name''Ming'.

    'age'18.

    'skills''python'.

    'english''CET6'.

    'major''accounting'.

    'address''shenzhen'

}

Copy the code

1. If indent is not used, all information is displayed in one line

Json.dump; Json data must be in double quotes



with open("information_1_to_json.json"."w", encoding='utf-8'as f:

    Dump (dic_, f) # dump(dic_, f

    json.dump(information,   # Data to be written

              f, # File object

              sort_keys=True.# order of keys

              ensure_ascii=False)  # display Chinese

Copy the code

Take a look at the actual save:


Add indent to display multiple lines of data:

with open("information_2_to_json.json"."w", encoding='utf-8'as f:

    json.dump(information, 

              f, 

              indent=2.# space indent to write multiple lines

              sort_keys=True.

              ensure_ascii=False

Copy the code

json.loads

The two functions related to load convert JSON to Python data types as follows:

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

Json. loads convert jSON-formatted data to Python dictionary type data.

information1 = {

    'name''Ming'.

    'age'18.

    'address''shenzhen'

}

# dictionary is converted to JSON data

information3 = json.dumps(information1,ensure_ascii=False)



information11 = json.loads(information3)  # json to dictionary data

print(information11)

Copy the code

json.load

Open the JSON file and convert it to dictionary data

# using json. The load



with open("information_to_json.json",encoding="utf-8"as f:

    json_to_dict = json.load(f)  # json to a dictionary



print(json_to_dict)

Copy the code

Python data of other types is converted to JSON data

Json: dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps dumps

1. Tuple transformation


2. List transformation


3. Boolean value conversion


4. Numerical data transformation


Demjson

Demjson is a Python third-party library that can be used to encode and decode JSON data:

  • Encode: Encodes Python objects into JSON strings
  • Decode: Decodes an encoded JSON string into a Python object
Install demjson

Run PIP install demjson to install kan’dao. If the following interface is displayed, the installation is successful.


Using demjson

Import before using:

import demjson   # import packages

Copy the code

1. Coding function


2. Decoding function


An obvious drawback of the Demjson package is that it cannot parse Chinese data directly:


If we want to see Chinese data, we can use the eval function: