簡體   English   中英

CSV 到嵌套的 JSON Python

[英]CSV to nested JSON Python

我有一個 csv 文件,它只有一列由 200 行組成。 我想將每一行計數用作“優先級”,將每一行值用作“名稱”,獲得以下 json 格式:

[{ "model" : "mymodel",
   "pk" : ROW_ID,
   "fields":{
      "name" : ROW_VALUE,
      "priority" : ROW_ID
},
{ "model" : "mymodel",
   "pk" : ROW_ID,
   "fields":{
      "name" : ROW_VALUE,
      "priority" : ROW_ID
}]

我知道我必須使用csvjson ,但對嵌套的 json 格式很困惑。 這有什么幫助嗎?

您只需要打開文件並遍歷行。 您可以使用enumerate()獲取行號的值(從零開始)。 構建一個字典數組並將其傳遞給json.dumps以生成一個 JSON 字符串:

import json

with open(filePath) as f:
    next(f) #skip the header
    l = []
    for line, value in enumerate(f):
        l.append({
            "model" : "mymodel",
            "pk": line,
            "fields": {
                "name": value.strip(),
                "priority": line
            }
        })
print(json.dumps(l))
# or for indented output like below:
# json.dumps(l, indent=2) 

這將打印:

[
  {
    "model": "mymodel",
    "pk": 1,
    "fields": {
      "name": "Afghanistan",
      "priority": 0
    }
  },
  {
    "model": "mymodel",
    "pk": 2,
    "fields": {
      "name": "Albania",
      "priority": 1
    }
  },
  ...
]

暫無
暫無

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

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