Home > Enterprise >  Save Python dictionary to the JSON format (adding names)
Save Python dictionary to the JSON format (adding names)

Time:05-24

I filtered and processed some data and I got it in the following format:

{'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)]
...
}

Now, I want to save it to the JSON format, which I think should look this way (I'm not sure if I write suitable format, because such a JSON, I want to send to Grafana and make some graphs):

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}
    },
    ...
  ]
}

I appreciate any hints, how to get such a valid JSON format.

CodePudding user response:

formatting your data is quite simple:

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

the trick here is that your currency data is already in a perfect format to feed directly to dict

now all you have to do is

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

CodePudding user response:

working code:

  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)

output:

{
  "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"
      }
    }
  ]
}
  • Related