首页 > 解决方案 > Posting list to Json without square brackets in Python

问题描述

I'm trying to pass 10 country names at once to my payload by converting it to list. But i'm facing problems while executing the program as list comes with [square braces] that i'm unable to remove.

How can i send an entire list without square brackets to my payload. I tried json.dumps(payload) it's still not leaving the square braces.

format of my payload
payload= {"world" :
              {"continent": [
                              {"country": "HongKong"}
                            ],
                "planet": "earth"
              }
         }
my file-
file.csv
country
HongKong
USA
UK

how i expect the output to be-
payload= {"world" :
              {"continent": [
                              {"country": "HongKong"},{"country":"USA"}, 
                                                        {"country":"UK"}
                            ],
                "planet": "earth"
              }
         }

what i'm currently getting-
payload= {"world" :
              {"continent": [
                              {"country": ["HongKong","USA","UK"]}
                            ],
                "planet": "earth"
              }
         }

标签: pythonpython-3.xlist

解决方案


您尝试做的事情是不可能的,因为那是一本字典,它只能有一个值和一个键,在您的情况下是 Country 的键,该值只能是一个项目,因此为什么它作为列表传递。但是,您可以做的是使用 .join() 方法将列表转换为单个字符串,可能类似于“,”.join(name_of_list)。然后,您的字典将包含以下条目:“国家”:“香港、美国等”</p>


推荐阅读