How to add sub item to json in for loop

Question:

I am trying to achieve the following json output:

output2

My current code:

#!/usr/bin/env python3.9
import json

complete_lst = []
url_lst = ['https://', 'https://', 'https://']
complete_lst.append({'title': 'Hello'})

for url in url_lst:
  complete_lst.append({'watch': {'Season1': {'url': url}}
                     })

with open("Hello.json", "w") as file:
   json.dump(complete_lst, file)

the output json file looks like this :

output1

I want all the urls to be nested under watch->Season1->url key

Asked By: ghost239

||

Answers:

Try this:

import json

complete_lst = []
url_lst = ['https://', 'https://', 'https://']
complete_lst.append({
    'title': 'Hello',
    'watch': {'Season1':{"url":[]}}
})


for url in url_lst:
  complete_lst[0]["watch"]["Season1"]["url"].append(url)

print(complete_lst)

If your data is static then just do that:

import json

complete_lst = [{
    'title': 'Hello',
    'watch': {'Season1':{"url":['https://', 'https://', 'https://']}}
}]

print(complete_lst)
Answered By: Niyaz

Another way of doing this would be to build a dictionary instead of list:

#!/usr/bin/env python3.9
import json

url_lst = ['https://', 'https://', 'https://']
complete_list = {}
complete_list['title'] = "Hello"
complete_list['watch'] = {}
complete_list['watch']['Season1'] = {}
complete_list['watch']['Season1']['urls'] = []


for url in url_lst:
    complete_list['watch']['Season1']['urls'].append(url)

    
    
with open("Hello.json", "w") as file:
   json.dump(complete_list, file)

Note: Here you don’t need to access item by their indices and can directly use keys

Answered By: ReKx
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.