正在解码字符串内的json消息

iyzzxitl  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(160)

我有以下解码功能;

def flatten_data(json_data):
    """
    Arguments:
        json_data (dict): json data
    Returns:
        dict : {a:1, b:2, b_c:1, b_d:2}
    """
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            out[name[:-1]] = x
        else:
            out[name[:-1]] = x

    flatten(json_data)
    return out

如果我给这个函数提供如下JSON主体输入;

{
  "id": "123",  
  "name": "Jack",  
  "createdAt": 20221212,  
  "region": '{"country": "USA", "city": "NewYork"}'
}

我需要得到如下输出;

{
  "id": "123",  
  "name": "Jack",  
  "createdAt": 20221212,  
  "region_country": "USA",
  "region_city": 'NewYork'
}

如何修改flatten_data函数?

46qrfjad

46qrfjad1#

因为您在json_data中的“region”键提供了str数据而不是dict,这就是为什么您得到了错误的JSON值。请尝试将其设置为dict。
试试这个数据

json_data = {
  "id": "123",  
  "name": "Jack",  
  "createdAt": 20221212,  
  "region": {"country": "USA", "city": "NewYork"}
 }
j8ag8udp

j8ag8udp2#

您可以通过修改现有代码(其中的值为str)来实现这一点,因为在本例中,region\有引号""。因此,您可以使用内置的json模块来处理这一问题。

import json

def flatten_data(json_data):
    """
    Arguments:
        json_data (dict): json data
    Returns:
        dict : {a:1, b:2, b_c:1, b_d:2}
    """
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            out[name[:-1]] = x
        elif type(x) is str:
            try:
                y = json.loads(x)
                flatten(y, name)
            except:
                out[name[:-1]] = x
        else:
            out[name[:-1]] = x

    flatten(json_data)
    return out

json_data = {
  "id": "123",  
  "name": "Jack",  
  "createdAt": 20221212,  
  "region": '{"country": "USA", "city": "NewYork"}'
}

print(flatten_data(json_data))
    • 输出:**
{
  "id": "123",  
  "name": "Jack",  
  "createdAt": 20221212,  
  "region_country": "USA",
  "region_city": 'NewYork'
}

相关问题