简体   繁体   中英

Take a map() created in Python and format the data value to create a .json file

The final part of my code to create a readable file is this:

if __name__ == "__main__":
    try:
        with open("Lista_de_Links.json", "w+", newline="", encoding="UTF-8") as f:
            trio.run(main)
            links = map(lambda x: mainurl+x, allin)
            f.write(str(list(links)))

Where mainurl are the https://example.com values and allin are the values /value1 , /value2 , /value3 (and so on)

Within the file that saves the data, they are saved in this template:

['https://example.com/value1','https://example.com/value2','https://example.com/value3']

I tried to use json.dump() but the error TypeError: Object of type map is not JSON serializable delivered, my attempt:

if __name__ == "__main__":
    try:
        trio.run(main)
        links = map(lambda x: mainurl+x, allin)
        out_file = open("Lista_de_Links.json", "w+")
  
        json.dump(links, out_file, indent = 6)
        out_file.close()

Is there any method that I can format this data model to convert to a JSON read model without needing to edit my data creation code?

Convert the map to a list, just like you do when you use f.write(str()) .

        json.dump(list(links), out_file, indent = 6)

Of course, you could have just used a list comprehension instead of map() in the first place:

links = [mainurl+x for x in allin]

Any time you call map() with a lambda , a list comprehension will be simpler.

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