[英]How to convert json to required format
我正在嘗試使用Google圖表可視化一些數據。 我正在通過對公開可用數據進行查詢來獲取此數據。 我在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'],
.....
]
我該怎么做呢? 我也剛剛意識到Google圖表可能需要對年齡進行排序? 最好的方法是什么? 在查詢本身?
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
函數創建新的sorted list, 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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.