如何将json转换为所需格式

2024-04-24 00:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用谷歌图表来可视化一些数据。我通过对一个公开可用的数据进行查询来获取这些数据。我是用python做的。这是我的密码

query_string = 'SELECT state, count(*) FROM [{0}] GROUP by state;'.format(_DATABASE_NAME)
births = self.run_query(query_string, filename='data/states.json')
# rows = births[u'rows']
#logging.info(births)
ages= []

states.insert(0, ('Age','No of occurences'))
logging.info(json.encode(ages))
context = {"states": json.encode(ages)}

在启动查询之后,这就是我在JSON文件中得到的结果

[
    {
        "f0_": "6170247",
        "mother_age": "31"
    },
    {
        "f0_": "6876756",
        "mother_age": "30"
    },
    {
        "f0_": "8271245",
        "mother_age": "26"
    }
]

为了可视化,我需要以下格式的数据-

[
   ['Age', 'No of occurences'],
   ['31', '6170247'],
   ['30', '6876756'],
   .....
]

我该怎么做?而且我刚刚意识到谷歌图表可能需要对年龄进行排序?最好的办法是什么?在查询本身中?你知道吗


Tags: 数据jsonagestring可视化logging图表query
3条回答
data = [
    {
        "f0_": "6170247",
        "mother_age": "31"
    },
    {
        "f0_": "6876756",
        "mother_age": "30"
    },
    {
        "f0_": "8271245",
        "mother_age": "26"
    }
]

编辑:如@Matthew所述,如果您在json文件中有数据,您可以使用json模块加载此数据。你知道吗

import json
with open(<path_to_json>) as fname:
    data = json.load(fname)

转换数据

迭代字典列表,即data,并将它们添加到列表中

new_list = []
for item in data:
    new_list.append([data["mother_age"], data["f0_"]])

# new_list  > [['31', '6170247'], ['30', '6876756'], ['26', '8271245']]

对列表排序

您可以对该列表进行适当排序

new_list.sort(key=lambda sublist: sublist[0])
# new_list  > [['26', '8271245'], ['30', '6876756'], ['31', '6170247']]

或者使用sorted函数创建一个新的排序列表,new_list将不会更改

final_list = sorted(new_list, key=lambda sublist: sublist[0])
# new_list  > [['31', '6170247'], ['30', '6876756'], ['26', '8271245']]
# final_list  > [['26', '8271245'], ['30', '6876756'], ['31', '6170247']]

或者可以使用itemgetter而不是sorted

from operator import itemgetter
final_list = sorted(new_list, key=itemgetter(0))

使用json模块加载,然后对其进行迭代以生成所需的结构:

import json

with open(<json-file>) as jfile:
    jdata = json.load(jfile)

data = [['Age', 'No of occurences']]
for d in jdata:
    data.append([d['mother_age'], d['f0_']])

对查询中的数据进行排序肯定会更好,但对json数据进行排序也很容易:

for d in sorted(jdata, key=lambda x: x['mother_age']):
    ...

我会在Json上创建一个字典和一个循环来获得您想要的格式,比如:

data = [
    {
        "f0_": "6170247",
        "mother_age": "31"
    },
    {
        "f0_": "6876756",
        "mother_age": "30"
    },
    {
        "f0_": "8271245",
        "mother_age": "26"
    }
]
well_formated_data = []
well_formated_data.append(['Age','No of occurences'])

for elem in data:
    new_array = []
    new_array.append(elem['mother_age'])
    new_array.append(elem['f0_'])
    well_formated_data.append(new_array)

我检查了代码,结果是:

well_formated_data = [['Age', 'No of occurences'], ['31', '6170247'], ['30', '6876756'], ['26', '8271245']]

相关问题 更多 >