简体   繁体   English

取一个在 Python 中创建的 map() 并格式化数据值以创建一个 .json 文件

[英]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)其中mainurlhttps://example.com值, allin是值/value1/value2/value3 (等等)

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:我尝试使用json.dump()但错误TypeError: Object of type map is not JSON serializable交付,我的尝试:

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?有什么方法可以格式化这个数据模型以转换为JSON读取模型而无需编辑我的数据创建代码?

Convert the map to a list, just like you do when you use f.write(str()) .将映射转换为列表,就像使用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:当然,您可以首先使用列表推导而不是map()

links = [mainurl+x for x in allin]

Any time you call map() with a lambda , a list comprehension will be simpler.任何时候用lambda调用map()时,列表推导都会更简单。

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

相关问题 如何在python中采用json格式 - how to take json format in python 如何创建用python创建的数据的csv文件 - How to create a csv file of data created in python 如何使用python将具有键值对的已抓取json数据保存为json文件格式 - How to save scraped json data with key value pair into a json file format using python 基于其他 JSON 数据在 JSON 中创建文件树格式 - Create a file tree format in JSON based on other JSON data 如何创建一个将在python中以JSON格式序列化的数据结构? - How do I create a data structure that will be serialized this JSON format in python? 如何创建一个以 json 格式提取数据并将其存储在 csv 文件中的循环? - How to create a loop that extract data in json format and store it in a csv file? 使用 python 将 Firebase 用户数据导出为 Json 文件格式 - Exporting Firebase Users Data to Json file format using python - 从excel文件中读取数据并在python中以json格式返回响应 - - read data from excel file and return response in json format in python 使用python将JSON格式的文件数据加载到表中 - Loading JSON format file data to a table using python 使用 Python 将 CSV 文件数据转换为 JSON 格式 - Convert CSV file data into JSON format using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM