Home > Software design >  Python creating JSON object from string
Python creating JSON object from string

Time:12-22

I'm new to Python and trying to generate a list of dictionaries in JSON format. I get the data from Selenium by iterating through an element. I get the output as string. Here's my selenium snippet:

Company = driver.find_elements_by_xpath("//*[@class='au-target company']")
Category = driver.find_elements_by_xpath("//*[@class='job-category']")

I get my data by using a for loop like this:

for value in Company:
    print(value.text)

for value in Category:
    print(value.text)

Here are my results:

Company A
Company B
Company C
Digital Technology
Manufacturing
Supply Chain

I would like to have my data in the following format

[
    {
        "Company": "Company A",
        "Category": "Digital Technology"
    },
    {
        "Company": "Company B",
        "Category": "Manufacturing"
    },
    {
        "Company": "Company C",
        "Category": "Supply Chain"
    }
]

So far I have been unsuccessful using the json module. Thanks!

CodePudding user response:

You can handle it like this

d = []
for company, category in zip(Company, Category):
    d.append({
        "company": company.text,
        "category": category.text
    })

or

d = [
    {"company": company.text, "category": category.text}
    for company, category in zip(Company, Category)
]

CodePudding user response:

Try this,

data = []
for comp, cat in zip(Company, Category):
    data.append({'Company':comp, 'Category': cat})

Output:

data
[
    {
        "Company": "Company A",
        "Category": "Digital Technology"
    },
    {
        "Company": "Company B",
        "Category": "Manufacturing"
    },
    {
        "Company": "Company C",
        "Category": "Supply Chain"
    }
]

CodePudding user response:

One liner solution

d= [{"Company":company,"Category":category} for company,category in zip(Company,Category)]
  • Related