简体   繁体   English

将 Python 列表转换为 Json 对象

[英]Convert Python list to Json object

I have three lists emojiLink , emojiTitle , emojiDescription in my code below.我在下面的代码中有三个列表emojiLinkemojiTitleemojiDescription

from bs4 import BeautifulSoup
import pandas as pd

r = requests.get("https://www.emojimeanings.net/list-smileys-people-whatsapp")

soup = BeautifulSoup(r.text, "lxml")

emojiLink = []
emojiTitle = []
emojiDescription = []

for tableRow in soup.find_all("tr", attrs={"class": "ugc_emoji_tr"}):
    for img in tableRow.findChildren("img"):
        emojiLink.append(img['src'])



for tableData in soup.find_all("td"):
    for boldTag in tableData.findChildren("b"):
        emojiTitle.append(boldTag.text)

for tableRow in soup.find_all("tr", attrs={"class": "ugc_emoji_tr"}):
    for tabledata in tableRow.findChildren("td"):
        if tabledata.has_attr("id"):
            k = tabledata.text.strip().split('\n')[-1]
            l = k.lstrip()
            emojiDescription.append(l)

I want to convert these lists into a Json object which gonna look like...我想将这些列表转换成一个 Json 对象,它看起来像......

{{"link": "emojiLink[0]", "title": "emojiTitle[0]", "desc": "emojiDescription[0]"},{"link": "emojiLink[1]", "title": "emojiTitle[1]", "desc": "emojiDescription[1]"}..........} so on...

I am not getting to how to do this?我不知道该怎么做?

THANKS IN ADVANCE!!!提前致谢!!!

One by one access each element from list and put it into some dict and at the end append to a list:逐个访问列表中的每个元素并将其放入某个字典中,最后附加到列表中:

import json

# some example lists
em_link = ['a', 'b', 'c']
em_title = ['x', 'y', 'z']
em_desc = [1,2,3]

arr = []
for i,j,k in zip(em_link, em_title, em_desc):
    d = {}
    d.update({"link": i})
    d.update({"title": j})
    d.update({"desc": k})
    arr.append(d)

print(json.dumps(arr))

Output:输出:

[{"link": "a", "title": "x", "desc": 1}, {"link": "b", "title": "y", "desc": 2}, {"link": "c", "title": "z", "desc": 3}]

This returns an array of JSON objects based off of Chandella07's answer.这将根据 Chandella07 的回答返回一组 JSON 对象。

from bs4 import BeautifulSoup
import pandas as pd
import requests
import json

r = requests.get("https://www.emojimeanings.net/list-smileys-people-whatsapp")

soup = BeautifulSoup(r.text, "lxml")

emojiLinkList = []
emojiTitleList = []
emojiDescriptionList = []
jsonData = []

for tableRow in soup.find_all("tr", attrs={"class": "ugc_emoji_tr"}):
    for img in tableRow.findChildren("img"):
        emojiLinkList.append(img['src'])

for tableData in soup.find_all("td"):
    for boldTag in tableData.findChildren("b"):
        emojiTitleList.append(boldTag.text)

for tableRow in soup.find_all("tr", attrs={"class": "ugc_emoji_tr"}):
    for tabledata in tableRow.findChildren("td"):
        if tabledata.has_attr("id"):
            k = tabledata.text.strip().split('\n')[-1]
            l = k.lstrip()
            emojiDescriptionList.append(l)

for link, title, desc in zip(emojiLinkList, emojiTitleList, emojiDescriptionList):
    dict = {"link": link, "title": title, "desc": desc}
    jsonData.append(dict)

print(json.dumps(jsonData, indent=2))

Data Example:数据示例:

{
    "link": "https://www.emojimeanings.net/img/emojis/purse_1f45b.png",
    "title": "Wallet",
    "desc": "After the shopping trip, the money has run out or the wallet was forgotten at home. The accessory keeps loose money but also credit cards or make-up. Can refer to shopping or money and stand for femininity and everything girlish."
  },

There is something wrong with your dict format.您的 dict 格式有问题。 {{...},{...}} is not a valid format, [{...},{...}] is valid. {{...},{...}}不是有效的格式, [{...},{...}]是有效的。

Regarding the merging logic:关于合并逻辑:

for i in zip([1,2,3], ["a", "b"], [8,9,10]):
    print(i)

... will output ... ... 将输出 ...

(1, 'a', 8)
(2, 'b', 9)

Try something like that:尝试这样的事情:

out = []
for i in zip(emojiLink, emojiTitle, emojiDescription):
    out.append({"link": i[0], ...})

You can use the json library to read/write in json format.您可以使用json库以 json 格式读取/写入。

import json

with open('./smthn.json', 'w') as f:
    json.dump({"a": "dictionary"}, f)

https://devtut.github.io/python/json-module.html#storing-data-in-a-file https://devtut.github.io/python/json-module.html#storing-data-in-a-file

So, you want a list of dictionary records?那么,您想要一个字典记录列表吗? If you're sure all of the lists are the same length, you can do:如果您确定所有列表的长度相同,您可以执行以下操作:

gather = []
for l,t,d in zip(emojiLink,emojiTitle,emojiDescription):
    gather.append( {"link":l, "title":t, "desc":d} )
json.dump( gather, open("myrecord.json","w") )

I'm currently testing on how github copilot would answer stackoverflow questions.我目前正在测试 github copilot 如何回答 stackoverflow 问题。

[ Your previous code here ]

# Explain what the code does:
# I have a list of dictionaries.
# I want to convert this list into a json object.
# I am using the json.dump() function to dump my list into a json file.

# I have my code below

import json
# Convert lists to json object

emoji = {}

for i in range(len(emojiLink)):
    emoji[i] = {
        "link": emojiLink[i],
        "title": emojiTitle[i],
        "desc": emojiDescription[i]
    }

# Save to json file

with open("emoji.json", "w") as f:
    json.dump(emoji, f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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