简体   繁体   中英

How to serialize an array into json object?

I am writing a web scraper that gets a car_id and all of its images:

car_id = 12345
images = []
image_list = self.driver.find_elements_by_css_selector('.carousel-inner a img')
for img in image_list:
    img_url = img.get_attribute('src')
    if img_url:
        images.append(img_url)

The output of the program is a json object, containing car_id and a list of its images... but how do I serialize the python array into the following json object?

item = {
    'car_id': car_id,
    'images': ["img1", "img2", ...] # serialize images array 
}
car_id = 12345
images = ['url1', 'url2', 'url3'] #list of image urls

item = {
    'car_id' : car_id,
    'images' : images
}

The item dict can be edited using

item['images'].append('url4')

If instead the images list has actual image objects (serialized into bytes or some other format), then the images list can contain those objects.

The variable item will be of type dict in python. This may be sufficient for your use case. If not then you may want to convert it to json string .

import json
result = json.dumps(item)

result will have the required json string.

initialize the item then use item['images'].append(img_url)

items = []

for id in listID:
    item = {
      "car_id": id, # 12345
      "images" = []
    }
    
    image_list = self.driver.find_elements_by_css_selector('.carousel-inner a img')
    for img in image_list:
        img_url = img.get_attribute('src')
        if img_url:
            item['images'].append(img_url)
            
    items.append(item)
    
print(items)

'''
[{
    'car_id': 12,
    'images': ["img1", "img2", ...] 
},
{
    'car_id': 23,
    'images': ["img1", "img2", ...]
}]
'''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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