Home > Mobile >  How can I make long tuple list of URLs separate into JSON objects?
How can I make long tuple list of URLs separate into JSON objects?

Time:12-06

I have a long tuple list of URLs that I would like to convert to JSON format in a specific way that allows each tuple item to be in their own nested object.

Kinda puzzled at how to manage to do that. I'm trying to convert the tuple into JSON so that it looks as such...

        "links": [
            {
                "src": tuple-item-1
            },
            {
                "src": tuple-item-2
            },
            {
                "src": tuple-item-3
            }
            ...
        ]

Thanks in advance :)

CodePudding user response:

import json
# Define a tuple of URLs
tuple = ("https://example.com/1", "https://example.com/2", "https://example.com/3")

# Create a list of dictionaries to hold the URLs
links = []

# Loop through the tuple items
for item in tuple:
    # Create a dictionary to hold the URL
    link = {"src": item}

    # Add the dictionary to the list
    links.append(link)

# Create a dictionary to hold the links
dictionary = {"links": links}

# Convert the dictionary to a JSON string
json = json.dumps(dictionary)

print(json)

CodePudding user response:

If you have lists/truples of links like this: ['www.ex1.com', .. , 'www.exn.com']

then we can use list compression:


import json
# Define a tuple of URLs
tuples = ("https://example.com/1", "https://example.com/2", "https://example.com/3")

# Create a list of dictionaries 
links = list({"src": i} for i in truples)

# Convert the list into json
jsons = json.dumps(dictionary)


# Either print it
print(jsons)

# Or save it
with open('file.json', 'w') as fl: json.dump(jsons)

  • Related