Python complete newbie, JSON formatting
<p>I have never used Python before but am trying to use it due to some restrictions in another (proprietary) language, to retrieve some values from a web service and return them in json format to a home automation processor. The relevant section of code below returns :</p>

<pre><code>[u'Name:London', u'Mode:Auto', u'Name:Ling', u'Mode:Away']
["Name:London", "Mode:Auto", "Name:Ling", "Mode:Away"]
</code></pre>

<p>â¦which isn't valid json. I am sure this is a really dumb question but I have searched here and haven't found an answer that helps me. Apologies if I missed something obvious but can anyone tell me what I need to do to ensure the json.dumps command outputs data in the correct format?</p>

<pre><code>CresData = []
for i in range(0, j):
    r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/installationInfo?userId=%s&amp;includeTemperatureControlSystems=True' % UserID, headers=headers)

    CresData.append("Name:" + r.json()[i]['locationInfo']['name'])

    r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/%s/status?includeTemperatureControlSystems=True' % r.json()[i]['locationInfo']['locationId'], headers = headers)

    CresData.append('Mode:' + r.json()['gateways'][0]['temperatureControlSystems'][0]['systemModeStatus']['mode'])

Cres_json = json.dumps(CresData)
print CresData
print Cres_json
</code></pre>

<p>I wasn't able to test the code as the link you mentioned is not a live link but your solution should be something like this</p>

<p>It looks like you are looking for JSON format with key value pair. you need to pass a dict object into json.dumps() which will return you string in required JSON format.</p>

<pre><code>CresData = dict()
key_str = "Location"
idx = 0
for i in range(0, j):
    data = dict()
    r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/installationInfo?userId=%s&amp;includeTemperatureControlSystems=True' % UserID, headers=headers)
        data["Name"] = r.json()[i]['locationInfo']['name']
    r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/%s/status?includeTemperatureControlSystems=True' % r.json()[i]['locationInfo']['locationId'], headers = headers)
        data["mode"] = r.json()['gateways'][0]['temperatureControlSystems'][0]['systemModeStatus']['mode']
    CresData[key_str + str(idx)] = data
    idx +=1

Cres_json = json.dumps(CresData)
print CresData
print Cres_json
</code></pre>

python json