json解析

1. json 模块提供了一种很简单的方式来编码和解码 JSON 字符串。其中两个主要有下面 4 个函数:

      1)pythonObj= json.loads(jsonStr): 已编码的 JSON 字符串解码为 Python 对象

      2)pythonObj = json.load(file): 用于从 json 文件中读取数据。

      3)jsonStr = json.dumps(pythonObj): 将 Python 对象编码成 JSON 字符串

      4)json.dump(pythonObj, file):将 Python 对象 写成 json 文件。

   python 原始类型向 json 类型的转化对照表:

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

   JSON 编码支持的基本数据类型为 None ,bool ,int ,float 和 str ,以及包含这些类型数据的 lists,tuples 和 dictionaries。

   下面来看一些例子:

json_str = json.dumps(data)
data = json.loads(json_str)

"""
一般来讲,JSON 解码会根据提供的数据创建 dicts 或 lists。如果你想要创建其他
类型的对象,可以给 json.loads() 传递 object_pairs_hook 或 object_hook 参数。例
如,下面是演示如何解码 JSON 数据并在一个 OrderedDict 中保留其顺序的例子:
"""
data = json.loads(s, object_pairs_hook=OrderedDict)

# Writing JSON data
with open('data.json', 'w') as f:
    json.dump(data, f)

# Reading data back
with open('data.json', 'r') as f:
    data = json.load(f)

 

2. 下面是如何将一个 JSON 字符串转换为一个 Python 对象例子:
import json

s = '{"name": "ACME", "shares": 50, "price": 490.1}'

class JSONObject:
    def __init__(self, d):
        self.__dict__ = d

data = json.loads(s, object_hook=JSONObject)
# key 变成属性
print(data.name)
print(data.shares)
print(data.price)

   json 字符串可以反序列化为 Python 对象,但通常 Python 对象实例并不是 JSON 可序列化的。例如:

import json

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(2, 3)
# json.dumps(p)     # 出错:Object of type Point is not JSON serializable

"""
如果你想序列化对象实例,你可以提供一个函数,它的输入是一个实例,返回一个
可序列化的字典。
"""

def serialize_instance(obj):
    d = { '__classname__' : type(obj).__name__ }
    d.update(vars(obj))
    return d

p = Point(2,3)
s = json.dumps(p, default=serialize_instance)
print(s)    # {"__classname__": "Point", "x": 2, "y": 3}

 

3. 一个查找 json 值的递归程序

key_list = ['key1', 'key2', 'key3', 'key4']

def is_key_match(key, suffix):
    if len(key) < len(suffix):
        return False
    length = len(suffix)
    if str(key[-length:]).lower() == str(suffix).lower():
        return True
    return False


def get_json_value(json_obj, key_lst, is_value_only):
    if isinstance(json_obj, dict):
        for key in json_obj.keys():
            if is_key_match(key, key_lst[0]):
                if len(key_lst) == 1:
                    if is_value_only:
                        return json_obj[key]
                    else:
                        return {key : json_obj[key]} # return a map
                res = get_json_value(json_obj[key], key_lst[1:], True)
                if is_value_only:
                    return res
                else:
                    return {key : res}
    if is_value_only:
        return ''
    else:
        return {}

  

posted @ 2020-07-05 20:36  _yanghh  阅读(232)  评论(0编辑  收藏  举报