20

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}
1
  • I'm confused... is that already JSON or a python dict? Those things look very similar. JSON stands for JavaScript Object Notation which is a way to serialize data to exchange among systems. There isn't such a thing as a "JSON object" but there are objects in programming languages like python and javascript that can be built from them. Is this a sting and you want a dict or is this a dict and you want a string? Commented Jan 9, 2017 at 7:23

2 Answers 2

31

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)
Sign up to request clarification or add additional context in comments.

6 Comments

The value of all the key i.e, user2_proximity, wifi_1 etc will be changing. Only thermostat and light value are constant.
@Anagha Update your question to be more specific, then. Read this.
@Anagha you can change the value by data['wifi_1'] = 2, then convert it into json again
This won't retain its order by the way, if you care about that.
@GrantFoster is there way to retain the order?
|
2

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" } }] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.