将单独的JSON数据列表合并为一个JSON数据

时间:2019-01-21 16:01:00

标签: python json pandas

在Python中,我试图打开一个单独的JSON数据列表:

[[{'id': 1, 'name': 'pencil', 'description': '2b or not 2b, that is the question'}], [{'id': 2, 'name': 'oil pastel', 'description': None}], [{'id': 3, 'name': 'gouache', 'description': None}], [{'id': 4, 'name': 'paper', 'description': None}]]

转换为一条JSON数据:

{'id': 1, 'name': 'pencil', 'description': '2b or not 2b, that is the question'}, {'id': 2, 'name': 'oil pastel', 'description': None}, {'id': 3, 'name': 'gouache', 'description': None}, {'id': 4, 'name': 'paper', 'description': None}, {'id': 5, 'name': 'coloured pencil', 'description': None}

努力奋斗了几个小时。有人有什么想法吗?

3 个答案:

答案 0 :(得分:1)

使用itertools.chain

>>> list(itertools.chain.from_iterable(j))

或者列表理解

>>> [x[0] for x in j] # Assuming there is only one item in each list

两个输出

[{'id': 1,
  'name': 'pencil',
  'description': '2b or not 2b, that is the question'},
 {'id': 2, 'name': 'oil pastel', 'description': None},
 {'id': 3, 'name': 'gouache', 'description': None},
 {'id': 4, 'name': 'paper', 'description': None}]

答案 1 :(得分:1)

使用简单的列表理解

[y for x in list_of_lists for y in x]

输出:

[{'description': '2b or not 2b, that is the question', 'id': 1, 'name': 'pencil'}, {'description': None, 'id': 2, 'name': 'oil pastel'}, {'description': None, 'id': 3, 'name': 'gouache'}, {'description': None, 'id': 4, 'name': 'paper'}]

答案 2 :(得分:1)

functoolsoperator一起使用

 j = [[{'id': 1, 'name': 'pencil', 'description': '2b or not 2b, that is the question'}], [{'id': 2, 'name': 'oil pastel', 'description': None}], [{'id': 3, 'name': 'gouache', 'description': None}], [{'id': 4, 'name': 'paper', 'description': None}]]


import functools
import operator
functools.reduce(operator.iadd,j,[])

输出:

[{'id': 1,
'name': 'pencil',
  'description': '2b or not 2b, that is the question'},
 {'id': 2, 'name': 'oil pastel', 'description': None},
 {'id': 3, 'name': 'gouache', 'description': None},
 {'id': 4, 'name': 'paper', 'description': None}]