简体   繁体   中英

how to parse data from multiple json fields and combine them in one list?

Lets assume I have 3 fields per object in a json file. They are

[{
    "morning" :   "[0, 1, 4, 6]",
    "afternoon" : "[0, 2, 3, 5, 6]",
    "evening" :   "[1, 4, 6]"
},
    .
    .
    .
{
    "morning" :   "[3, 5, 6]",
    "afternoon" : "[0, 2, 6]",
    "evening" :   "[1, 4, 6]"
}]

Here, 0 = sunday, 1 = monday, . . . . 6 = saturday

.
I want to parse the json file in such a way, where instead of 3 fields (morning, afternoon, evening) I will have only 1 field named schedule which is a list of 21 elements. Because I have 3 times in a day and 7 days in a week. which gives me the number 21.

I want the end result to be like this,

"schedule" : "[sm, sa, se, mm, ma, me, tm, ta, te, wm, wa, we, thm, tha, the, fm, fa, fe, sam, saa, sae]"

here sm = sunday_morning, ma = monday_afternoon, the = thursday_evening

OUTPUT EXAMPLE FOR 1ST OBJ:

"schedule" : [true, true, false, true, false, false, false, true, false, false, true, false, true, false, true, false, true, false, true, true, true]

You can iterate over each day (in this case 7 days) and then check if the current day is present in the mentioned arrays (morning, afternoon and evening) or not. If it is present, you can append true in a list variable, or else false .

You will have to check for each condition, ie morning, afternoon and evening to append the availability for each day.

As requested, to successfully parse, Null (empty/None) values in your JSON Data, You need to first check whether the field is empty or not. If it is empty, simply append false and continue for next condition, each for the three timings (morning, afternoon and evening).

As per your requirement, here is a sample code which may help:

import json

# Sample JSON Input
input = '{"morning":[],"afternoon":null,"evening":"[1, 4, 6]"}'

jsonInput = json.loads(input)

# Start processing
schedule = []

for x in range(0, 7):

    if jsonInput['morning'] is None:
        schedule.append('false')
    else:
        if str(x) in jsonInput['morning']:
            schedule.append('true')
        else:
            schedule.append('false')
    if jsonInput['afternoon'] is None:
        schedule.append('false')
    else:
        if str(x) in jsonInput['afternoon']:
            schedule.append('true')
        else:
            schedule.append('false')
    if jsonInput['evening'] is None:
        schedule.append('false')
    else:
        if str(x) in jsonInput['evening']:
            schedule.append('true')
        else:
            schedule.append('false')

print(jsonInput)
print(schedule)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM