将 Python 字典保存为 JSON 格式(添加名称)

Save Python dictionary to the JSON format (adding names)

我过滤并处理了一些数据,得到了以下格式的数据:

{'2020-04-20': [('EUR', 34.02), ('USD', 30.18), ('AWG', 24.44), ('GPB', 20.68)], 
 '2020-04-25': [('EUR', 16.88), ('USD', 15.06), ('AWG', 12.17), ('GPB', 10.4)], 
 '2020-04-27': [('EUR', 17.14), ('GPB', 10.28), ('USD', 7.58), ('AWG', 5.06), ('CZK', 2.44)]
...
}

现在,我想保存成JSON格式,我觉得应该是这样的(我不确定我写的格式是否合适,因为这样的JSON,我想发送到 Grafana 并制作一些图表):

json_data = {
  "filtered_data": [
    {
      "data": "2015-01-04",
      "currencies": {
        "EUR": 34.02,
        "USD": 30.18,
        "AWG": 24.44,
        "GPB": 20.68}
    },
    {
      "data": "2015-01-25",
      "currencies": {
        "EUR": 16.88,
        "USD": 15.06,
        "AWG": 12.17,
        "GPB": 10.4}
    },
    ...
  ]
}

我很感激任何提示,如何获得这样一个有效的 JSON 格式。

格式化数据非常简单:

filtered_data = [{"data": k, "currencies": dict(v)} for k, v in data.items()]

这里的诀窍是您的货币数据已经采用完美的格式,可以直接提供给 dict

现在你所要做的就是

json.dumps({'filtered_data': filtered_data})

工作代码: 解决方案是从字典中获取信息并使用 字典理解使用 dict -键和值而不是元组中的信息方便地格式化数据。

  import json
    dict = {'2020-04-20': [('EUR', 34.02), ('USD', 30.18), ('AWG', 24.44), ('GPB', 20.68)], 
     '2020-04-25': [('EUR', 16.88), ('USD', 15.06), ('AWG', 12.17), ('GPB', 10.4)], 
     '2020-04-27': [('EUR', 17.14), ('GPB', 10.28), ('USD', 7.58), ('AWG', 5.06), ('CZK', 2.44)]
    }
    
    
    json_data = {"filtered_data":[]}
    
    
    for key,val in dict.items():
        temp_dict={"data":key,"currencies":{element[0]: str(element[1]) for element in val }}
        json_data["filtered_data"].append(temp_dict)
    
        
    json_data = json.dumps(json_data,indent=2)
    print(json_data)

输出:

{
  "filtered_data": [
    {
      "data": "2020-04-20",
      "currencies": {
        "EUR": "34.02",
        "USD": "30.18",
        "AWG": "24.44",
        "GPB": "20.68"
      }
    },
    {
      "data": "2020-04-25",
      "currencies": {
        "EUR": "16.88",
        "USD": "15.06",
        "AWG": "12.17",
        "GPB": "10.4"
      }
    },
    {
      "data": "2020-04-27",
      "currencies": {
        "EUR": "17.14",
        "GPB": "10.28",
        "USD": "7.58",
        "AWG": "5.06",
        "CZK": "2.44"
      }
    }
  ]
}