如何在 Python 中创建 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41542734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create JSON object in Python
提问by Anagha
Hi I need to create a JSON object in the following format. How to go about it
您好,我需要按以下格式创建一个 JSON 对象。如何去做
{"user2_proximity": 3, "Wifi_1": -80, "Wifi_2": -40, "Wifi_3": -40,
"thermostat": 18, "light": 0, "hour_of_day": 0, "user3_proximity": 3,
"user1_proximity": 1, "day_of_week": 1, "security": 0, "minute_of_hour": 9,
"Act_1": 1, "Act_2": 0, "Act_3": 0}
回答by Po Stevanus Andrianta
source : https://docs.python.org/2/library/json.html
来源:https: //docs.python.org/2/library/json.html
import json
data = {"user2_proximity": 3, "Wifi_1": -80, "Wifi_2": -40, "Wifi_3": -40,
"thermostat": 18, "light": 0, "hour_of_day": 0, "user3_proximity": 3,
"user1_proximity": 1, "day_of_week": 1, "security": 0, "minute_of_hour": 9,
"Act_1": 1, "Act_2": 0, "Act_3": 0}
json_data = json.dumps(data)
回答by Binoy S Kumar
responseis a 2d array with values for keys/columns ("test_id","querytext","metrics").
response是一个二维数组,其中包含键/列的值(“test_id”、“querytext”、“metrics”)。
[0]['testid1','query1','"metrics": { "ndcg@3": "1.0", "ndcg@7": "0.9" }']
[1]['testid2','query2','"metrics": { "ndcg@3": "1.0", "ndcg@7": "0.9" }']
[0]['testid1','query1','"metrics": { "ndcg@3": "1.0", "ndcg@7": "0.9" }']
[1]['testid2','query2','"metrics": { "ndcg@3": "1.0", "ndcg@7": "0.9" }']
column_names=("test_id","querytext","metrics")
json_response={}
for entry in response:
if entry[0] not in json_response:
json_response[entry[0]]=[]
json_element={}
json_element[column_names[1]]=entry[1]
json_element[column_names[2]]=json.loads(entry[2])
json_response[entry[0]].append(json_element)
return json.dumps(json_response)
Now json_responsewill be of following format
现在json_response将采用以下格式
{
"tesid1": [{
"querytext": "query1",
"metrics": {
"ndcg@3": "1.0",
"ndcg@7": "0.9"
}
}],
"testid2": [{
"querytext": "query2",
"metrics": {
"ndcg@3": "1.0",
"ndcg@7": "0.9"
}
}]
}
{
"tesid1": [{
"querytext": "query1",
"metrics": {
"ndcg@3": "1.0",
"ndcg@7": "0.9"
}
}],
"testid2": [{
"querytext": "query2",
"metrics": {
"ndcg@3": "1.0",
"ndcg@7": "0.9"
}
}]
}

