Python完成新手,JSON格式化

时间:2016-10-18 10:32:13

标签: python json

我之前从未使用过Python,但由于其他(专有)语言的某些限制,我试图使用它,从Web服务中检索一些值并将它们以json格式返回到家庭自动化处理器。以下代码的相关部分返回:

[u'Name:London', u'Mode:Auto', u'Name:Ling', u'Mode:Away']
["Name:London", "Mode:Auto", "Name:Ling", "Mode:Away"]

...这是无效的json。我确信这是一个非常愚蠢的问题,但我在这里搜索过,并没有找到帮助我的答案。抱歉,如果我错过了一些明显的东西,但有人可以告诉我我需要做些什么来确保json.dumps命令以正确的格式输出数据吗?

CresData = []
for i in range(0, j):
    r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/installationInfo?userId=%s&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

1 个答案:

答案 0 :(得分:0)

我无法测试代码,因为您提到的链接不是实时链接,但您的解决方案应该是这样的

看起来您正在寻找具有键值对的JSON格式。你需要将一个dict对象传递给json.dumps(),它将以所需的JSON格式返回字符串。

list: tcsInstanceObjects = tcsClient.updateServerStatus(tcsInstanceObjects);