'How can I seperate the JSON response data to list?

Data A

"data": {
 "authors": [
  {
    "name": "A1",
    "type": "AUTHOR"
  },
  {
    "name": "B1",
    "type": "AUTHOR"
  }
  {
    "name": "C1",
    "type": "ILLUSTRATOR"
  }
 ]
}

Data B

"data": {
 "authors": [
  {
    "name": "A2",
    "type": "AUTHOR"
  },
  {
    "name": "B2",
    "type": "ILLUSTRATOR"
  }
 ]
}

I want to get data of author, illustrator.

a_writer = []
a_illustrator = []
a_writers = []
a_illustrators = []

res = requests.get(xml)
data = res.json()

for d in data_list:
 a_writer.clear()
 a_illustrator.clear()

 for n in data['data']['authors']:
  print(n['type'])
  print(n['name'])
  if n['type'] == 'AUTHOR':
   writer = n['name']
   a_writer.append(writer)
  if n['type'] == 'ILLUSTRATOR':
   illustrator = n['name']
   a_illustrator.append(illustrator)

 a_writers.extend(a_writer)
 a_illustrators.extend(a_illustrator)

print(a_writers)
print(a_illustrators)

I wrote the code as above, it export like this.

author: ['A1', 'B1', 'A2']

illustrator: ['C1', 'B2']

If I use append instead extend it export like this.

authors: ['A2', 'A2']

illustrator: ['B2', 'B2]

How can I separate the data as below?

author: ['A1, B1', 'A2']

illustrator: ['C1', 'B2']



Solution 1:[1]

list = [] and list.clear() is different, latter won't re-create a new list. What you want is list = []

for data in data_list:
    a_writer = []
    a_illustrator = []

    for n in data['data']['authors']:
         if n['type'] == 'AUTHOR':
             writer = n['name']
             a_writer.append(writer)
         if n['type'] == 'ILLUSTRATOR':
             illustrator = n['name']
             a_illustrator.append(illustrator)

    a_writers.append(a_writer)
    a_illustrators.append(a_illustrator)

To get the output you want:

list(map(', '.join, a_writers))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ynjxsjmh