python 使用 json

简单json 编解码

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice","Bob"),
  "pets": ['Dog'],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
  ]
}

#json 编码
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

#json 解码
decode_string = json.loads(sorted_string)
print(decode_string["age"])
print(decode_string["cars"][0]["model"])

输出:

root@default:/share# python3 demo1.py 
{
    "age": 45,
    "cars": [
        {
            "model": "Audi A1",
            "mpg": 15.1
        },
        {
            "model": "Zeep Compass",
            "mpg": 18.1
        }
    ],
    "children": [
        "Alice",
        "Bob"
    ],
    "married": true,
    "name": "Ken",
    "pets": [
        "Dog"
    ]
}
45
Audi A1
  • sort_keys是告诉编码器按照字典key排序(a到z)输出

  • indent参数根据数据格式缩进显示,读起来更加清晰, indent的值,代表缩进空格式:

  • 输出真正的中文需要指定ensure_ascii=False

自定义编码转换方式

JSONEncoder默认转换方式:

    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

自定义,继承json.JSONEncoder,添加对numpy以及time的支持

import json
import numpy as np
import time

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        if isinstance(obj, time):
            return obj.__str__()
        else:
            return super(MyEncoder, self).default(obj)

two_arr = np.array([
     [1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]
 ])

data = {
    "Url": "http:127.0.0.0/xzw",
    "array": two_arr,
    "time": time.time(),
}

encode_string=json.dumps(data, ensure_ascii=False, cls=MyEncoder)
print(encode_string)

输出:

root@default:/share# python3 demo2.py 
{"Url": "http:127.0.0.0/xzw", "array": [[1, 2, 3], [4, 5, 6], [7, 8, 9]], "time": 1599534773.0939293}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×