Hi I need to create a JSON object in the following format. How to go about it
{"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}
To create an object we need to use opening and closing curly braces {} and then inside of that we'll put all of the key value pairs that make up our object. Every single property inside the JSON is a key value pair. The key must be surrounded by double "" quotes followed by a colon : and then the value for that key.
To convert string to json in Python, use the json. loads() function. The json. loads() is a built-in Python function that accepts a valid json string and returns a dictionary to access all elements.
source : https://docs.python.org/3/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)
response
is a 2d array with values for keys/columns ("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" }']
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_response
will be of following format
{
"tesid1": [{
"querytext": "query1",
"metrics": {
"ndcg@3": "1.0",
"ndcg@7": "0.9"
}
}],
"testid2": [{
"querytext": "query2",
"metrics": {
"ndcg@3": "1.0",
"ndcg@7": "0.9"
}
}]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With