简体   繁体   English

如何使用 python 创建 json 对象数组

[英]How do I create json array of objects using python

I have a list of countries and their cities on one website.我在一个网站上有一份国家及其城市的列表。 I take all names of countries and their capitals from this list, and want to put them in JSON file like this:我从此列表中获取所有国家及其首都的名称,并希望将它们放入 JSON 文件中,如下所示:

[
  {
    "country": "Afghanistan",
    "city": "Kabul"
  },
  {
    "country": "Aland Islands",
    "city": "Mariehamn"
  }
]

there's my code:这是我的代码:

cells = soup.table('td')
count = 0

cities_list.write('[\n')

for cell in cells:
    if count == len(cells)-2:
        break
    else:
        cities_list.write(json.dumps({"country": "{}".format(cells[count].getText()),
                                      "city": "{}".format(cells[count].next_sibling.getText())},
                                       indent=2))
    count += 2

cities.list_write('\n]')

And my problem is that objects are not separated by comma:我的问题是对象没有用逗号分隔:

[
{
  "country": "Afghanistan",
  "city": "Kabul"
}{
  "country": "Aland Islands",
  "city": "Mariehamn"
}
]

How can I make my objects separated by comma, and also is it possible to do without writing '\n]' at the end and beginning?如何使我的对象用逗号分隔,并且是否可以在结尾和开头不写'\n]'

Python obviously has no way to know that you are writing a list of objects when you are writing them one at a time... so just don't. Python 显然无法知道当您一次编写一个对象时您正在编写一个对象列表......所以不要。

cells = soup.table('td')

cities = []
for cell in cells[:-2]:
    cities.append({"country": str(cells[count].getText()),
                   "city": str(cells[count].next_sibling.getText())})

json.dump(cities, cities_list)

Notice also how "{}".format(value) is just a clumsy way to write str(value) (or just value if value is already a string) and how json.dump lets you pass an open file handle to write to.还要注意"{}".format(value)如何只是一种笨拙的方式来写入str(value) (或者如果value已经是一个字符串,则只是value )以及json.dump如何让您传递一个打开的文件句柄来写入。

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

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