【问题标题】:How to create JSON object in Python如何在 Python 中创建 JSON 对象
【发布时间】:2017-05-23 09:39:11
【问题描述】:

您好,我需要创建一个以下格式的 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}

【问题讨论】:

  • 我很困惑......那已经是 JSON 还是 python dict?这些东西看起来非常相似。 JSON 代表 JavaScript Object Notation,它是一种序列化数据以在系统之间交换的方式。没有“JSON 对象”之类的东西,但在 Python 和 javascript 等编程语言中可以使用它们构建对象。这是一个刺痛,你想要一个dict,还是这是一个dict,你想要一个字符串?

标签: json python-2.7


【解决方案1】:

来源: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)

【讨论】:

  • 所有键的值,即 user2_proximity、wifi_1 等都会发生变化。只有恒温器和光值是恒定的。
  • @Anagha 然后更新您的问题以更具体。阅读this
  • @Anagha 你可以通过data['wifi_1'] = 2改变值,然后再转换成json
  • 顺便说一句,这不会保留它的顺序,如果你关心的话。
  • @GrantFoster 有没有办法保留订单?
【解决方案2】:

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

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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2017-02-25
    • 2016-01-23
    • 2011-03-17
    • 2018-02-25
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多