【问题标题】:convert list array to json将列表数组转换为 json
【发布时间】:2022-09-24 00:22:59
【问题描述】:

我正在努力获取 JSON 提要并仅从列表中过滤掉我想要的项目。我正在将我想保留的项目附加到每个列表标识符中。但是,当我转换为 JSON 时,输出不正确。您可以在下面看到 ACTUAL OUTPUT 示例。下面的目标输出是我真正期待的。我试过用索引和记录来定位列表,但没有运气。

#TARGET OUTPUT
{
   \"id\":\"1\",
   \"Name\":\"xxx\",
   \"Image\":\"https://xxx.xxx.png\",
},
{
   \"id\":\"2\",
   \"Name\":\"xx2\",
   \"Image\":\"https://xx2.xxx.png\",
}



#ACTUAL OUTPUT
{
  \"id\": [\"1\",\"2\",]
},
{
  \"image\":[\"https://xxx.xxx.png\",\"https://xx2.xxx.png\"] 
},
{
  \"name\":[\"xxx\", \"xx2\"]
},

#CODE

# JSON feed
{
  \"document\": {
    \"id\": \"1\",
    \"image\": \"https://xxx.xxx.png\",
    \"name\": \"xxx\",
   },
 },
 {
  \"document\": {
    \"id\": \"2\",
    \"image\": \"https://xx2.xxx.png\",
    \"name\": \"xx2\",
   },
 },

# create list array
list = {\'id\':[], \'Name\': [], \'Image\': []}
links = {\'id\': [], \'Image\': []}

# loop through and append items
def getData(hits):
    for item in filter(None, hits):
        item = item[\'document\']
        list[\'id\'].append(item[\'id\'])
        links[\'id\'].append(item[\'id\'])
        links[\'Image\'].append(item[\'image\'])
        list[\'Image\'].append(item[\'image\'])
        list[\'Name\'].append(item[\'name\'])

    # get first page
    pageNum = 1
    data = getDataPerPage(pageNum)
    try:
        itemsNo = data[\'found\']
        getData(data[\'hits\'])

        while itemsNo > 24:
            itemsNo -= 24
            pageNum += 1
            data = getDataPerPage(pageNum)
            getData(data[\'hits\'])
    
    except:
        print(\"broken\")


    # save list to json
    with open(\'./output/data_chart.json\', \'w\') as f:
       f.write(json.dumps(list))
  • list 是 python 中的保留名称,所以你不应该使用它。尝试使用lst 之类的其他内容。
  • 哦,这很有意义。谢谢@MichaelM。
  • 这解决了你的问题吗?
  • 您的目标输出无效。它应该是字典列表吗?
  • 不完全是。它仍然在 id 中花费所有 ID,以及所有图像、图像。可能是@jarmod

标签: python python-3.x


【解决方案1】:

不是 100% 清楚您拥有什么或想要什么,但有一些假设(输入是 dict 列表,所需输出是 dict 列表):

json_obj = [
    {
        "document": {
            "id": "1",
            "image": "https://xxx.xxx.png",
            "name": "xxx",
        },
    },
    {
        "document": {
            "id": "2",
            "image": "https://xx2.xxx.png",
            "name": "xx2",
        },
    },
]

desired_output = [x["document"] for x in json_obj]
print(desired_output)

【讨论】:

    猜你喜欢
    • 2013-08-22
    • 1970-01-01
    • 2020-04-27
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2020-08-08
    • 2015-08-06
    相关资源
    最近更新 更多