SoFunction
Updated on 2025-03-02

Detailed explanation of Python’s Json module encoding

Functions can be used()Converts Python object encoding to string form.

For example:

import json 
python_obj = [[1,2,3],3.14,'abc',{'key1':(1,2,3),'key2':[4,5,6]},True,False,None] 
json_str=(python_obj)
print(json_str)

Output:

[[1, 2, 3], 3.14, "abc", {"key1": [1, 2, 3], "key2":
[4, 5, 6]}, true, false, null]

The string encoded by a simple type object is basically the same as its original repr() result, but some data types, such as the tuple (1, 2, 3) in the above example, are converted into [1, 2, 3] (the array form of the json module).
Some parameters can be passed to the function () to control the result of the conversion. For example, when the parameter sort_keys=True, data of type dict will be converted in an orderly manner according to the key (key):

data = [{'xyz': 3.0,'abc': 'get', 'hi': (1,2) },'world','hello'] 
json_str = (data)
print(json_str)
json_str = (data, sort_keys=True)
print(json_str)

Output:

[{"xyz": 3.0, "abc": "get", "hi": [1, 2]}, "world", "hello"]
[{"abc": "get", "hi": [1, 2], "xyz": 3.0}, "world", "hello"]

That is, when sort_keys=True, the converted json string is key-ordered for the elements of the dictionary.
For structured data, you can set a value (such as indent=3) to the parameter indent to generate a json string with indent and good reading:

json_str = (data, sort_keys=True,indent = 3)
print(json_str)

Output:

[
    {
        "abc": "get",
        "hi": [
            1,
            2
        ],
        "xyz": 3.0
    },
    "world",
    "hello"
]

Summarize

That’s all for this article. I hope it can help you and I hope you can pay more attention to more of my content!