簡體   English   中英

如何從嵌套的 Json 中提取列表到 CSV?

[英]How to extract list from nested Json into a CSV?

我使用 API 輸出我的地址。 然而,地址是這樣嵌套的:

{
   "totalItemCount":55,
   "pageCount":1,
   "size":100,
   "_links":{
      "self":{
         "href":"\/bag?filters[postcode]=1011PL&ovio-api-key=KEY"
      }
   },
   "_embedded":{
      "adres":[
         {
            "huisnummer":"7",
            "huisletter":"",
            "postcode":"1011PL",
            "huisnummertoevoeging":"",
            "openbareruimte":"Nieuwe Amstelstraat",
            "slug":"1011pl-nieuwe-amstelstraat-7",
            "woonplaats":"Amsterdam",
            "_links":{
               "self":{
                  "href":"\/bag\/1011pl-nieuwe-amstelstraat-7"
               }
            }
         },
         {
            "huisnummer":"25",
            "huisletter":"",
            "postcode":"1011PL",
            "huisnummertoevoeging":"",
            "openbareruimte":"Nieuwe Amstelstraat",
            "slug":"1011pl-nieuwe-amstelstraat-25",
            "woonplaats":"Amsterdam",
            "_links":{
               "self":{
                  "href":"\/bag\/1011pl-nieuwe-amstelstraat-25"
               }
            }
         },

我當前的腳本:

## Convert Output JSON to CSV
f = open("output.json", "r+")
x = json.loads(f.read())
f.close()
# print(x['_embedded']['adres'][0]['openbareruimte'])

f = csv.writer(open("test.csv", "w"))
f.writerow(["straat","huisnummer","postcode","stad"])
for y in x:
    f.writerow([x["_embedded"]["adres"][0]["openbareruimte"],
                x["_embedded"]["adres"][0]["huisnummer"],
                x["_embedded"]["adres"][0]["postcode"],
                x["_embedded"]["adres"][0]["woonplaats"]])

我想將 output 的所有街道、號碼、郵政編碼和城市到 CSV,但它只輸出第一個地址。 我曾嘗試使用拆分和格式,但我對此太不熟悉了。 如果有人知道如何使用嵌套數據,將不勝感激。 我找不到任何有關的教程。

您想遍歷x["_embedded"]["adres"]中的項目並為每個y編寫項目

for y in x["_embedded"]["adres"]:
    f.writerow(y["openbareruimte"],
               y["huisnummer"],
               y["postcode"],
               y["woonplaats"])

首先, x似乎是一本字典。 所以for y in x: ...將遍歷鍵。 在這種情況下,它似乎是“totalItemsCount”、“pageCount”等。這顯然不是你想要的,因為你甚至沒有使用y

嵌入字段,正如您自己使用的那樣,是x["_embedded"]["adres"] 正如您所確定的,它是一個地址數組。 您只需要 go 就可以了:

addresses = x["_embedded"]["adres"]
for address in addresses:
    f.writerow([address["openbareruimte"],
        address["huisnummer"],
        address["postcode"],
        address["woonplaats"]])

關於您的代碼的更多評論:

  • 打開文件時,應始終將其用作上下文管理器,以便將其關閉: with open(...) as f: ... (原因是如果在 json 加載期間引發異常,則該文件是'沒有正確關閉)。
  • json可以直接從文件加載: json.load(f)

考慮到以上兩條評論,正確加載json的方法是:

with open("output.json", "r+") as f:
    x = json.load(f)
# no need to call "f.close()"

with open("test.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerow(["straat","huisnummer","postcode","stad"])
    addresses = x["_embedded"]["adres"]
    for address in addresses:
        f.writerow([address["openbareruimte"],
            address["huisnummer"],
            address["postcode"],
            address["woonplaats"]])

您需要遍歷加載的 JSON 數據中的列表。

## Convert Output JSON to CSV

import csv, json

with open("output.json", "r") as f:
    x = json.load(f)

with open("subtract_test.csv", "w", newline="") as outp:
    f = csv.writer(outp)
    f.writerow(["straat","huisnummer","postcode","stad"]) # Header.

    for adres in x["_embedded"]["adres"]:
        f.writerow([adres["openbareruimte"],
                    adres["huisnummer"],
                    adres["postcode"],
                    adres["woonplaats"]])

print("Done")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM