Home > Blockchain >  json string format done differently
json string format done differently

Time:02-08

I have 2 lists - dates and weekdays

>>> dates
['2022-02-08', '2022-02-09', '2022-02-10', '2022-02-11', '2022-02-12', '2022-02-13', '2022-02-14', '2022-02-15']
>>> weekdays
['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

I want to create a json object that looks like this (for eg) for each element in dates.

myjson = {"label": "Tuesday-2022-02-08", "value": "/inform_date{\"date_list\": \"2022-02-08\"}"}

Basically I want to run a loop where myjson looks like what is given above.

data = []
for i in range(len(dates)):
  myjson = {"label": "{0}-{1}".format(weekdays[i], dates[i]), "value": "/inform_date{\"date_list\": \"{}\"}".format(dates[i])}
  data.append(myjson)

but I get an error when I run the above for loop.

What is the correct way to build myjson so that it looks just like shown in the example above?

CodePudding user response:

Your second format string has 'spare' braces which need to be escaped:

myjson = {"label": "{0}-{1}".format(weekdays[i], dates[i]), "value": "/inform_date{{\"date_list\": \"{}\"}}".format(dates[i])}

CodePudding user response:

Use a comprehension and f-strings:

import json

data = [{'label': f"{w}-{d}", 'value': f'/inform_date{{"date_list": {d}}}'}
            for d, w in zip(dates, weekdays)]
print(json.dumps(data, indent=4))
[
    {
        "label": "Tuesday-2022-02-08",
        "value": "/inform_date{\"date_list\": 2022-02-08}"
    },
    {
        "label": "Wednesday-2022-02-09",
        "value": "/inform_date{\"date_list\": 2022-02-09}"
    },
    {
        "label": "Thursday-2022-02-10",
        "value": "/inform_date{\"date_list\": 2022-02-10}"
    },
    {
        "label": "Friday-2022-02-11",
        "value": "/inform_date{\"date_list\": 2022-02-11}"
    },
    {
        "label": "Saturday-2022-02-12",
        "value": "/inform_date{\"date_list\": 2022-02-12}"
    },
    {
        "label": "Sunday-2022-02-13",
        "value": "/inform_date{\"date_list\": 2022-02-13}"
    },
    {
        "label": "Monday-2022-02-14",
        "value": "/inform_date{\"date_list\": 2022-02-14}"
    },
    {
        "label": "Tuesday-2022-02-15",
        "value": "/inform_date{\"date_list\": 2022-02-15}"
    }
]
  •  Tags:  
  • Related