【问题标题】:Convert nested json to csv to sheets json api将嵌套的 json 转换为 csv 到工作表 json api
【发布时间】:2018-10-24 20:21:33
【问题描述】:

我想将我的 json 转换为 csv,以便我可以将其上传到 google 表格并使其成为 json api。每当我有更改数据时,我都会在谷歌表格上更改它。但是我在将我的 json 文件转换为 csv 时遇到问题,因为它会在我转换它时更改变量。我正在使用https://toolslick.com/csv-to-json-converter 将我的 json 文件转换为 csv。 将嵌套的 json 转换为 csv 的最佳方法是什么?

JSON

{
  "options": [
    {
      "id": "1",
      "value": "Jumbo",
      "shortcut": "J",
      "textColor": "#FFFFFF",
      "backgroundColor": "#00000"
    },
    {
      "id": "2",
      "value": "Hot",
      "shortcut": "D",
      "textColor": "#FFFFFF",
      "backgroundColor": "#FFFFFF"
    }
  ],
  "categories": [
    {
      "id": "1",
      "order": 1,
      "name": "First Category",
      "active": true
    },
    {
      "id": "2",
      "order": 2,
      "name": "Second Category",
      "shortcut": "MT",
      "active": true
    }
  ],
  "products": [
    {
      "id": "03c6787c-fc2a-4aa8-93a3-5e0f0f98cfb2",
      "categoryId": "1",
      "name": "First Product",
      "shortcut": "First",
      "options": [
        {
          "optionId": "1",
          "price": 23
        },
        {
          "optionId": "2",
          "price": 45
        }
      ],
      "active": true
    },
    {
      "id": "e8669cea-4c9c-431c-84ba-0b014f0f9bc2",
      "categoryId": "2",
      "name": "Second Product",
      "shortcut": "Second",
      "options": [
        {
          "optionId": "1",
          "price": 11
        },
        {
          "optionId": "2",
          "price": 20
        }
      ],
      "active": true
    }
  ],
  "discounts": [
    {
      "id": "1",
      "name": "S",
      "type": 1,
      "amount": 20,
      "active": true
    },
    {
      "id": "2",
      "name": "P",
      "type": 1,
      "amount": 20,
      "active": true
    },
    {
      "id": "3",
      "name": "G",
      "type": 2,
      "amount": 5,
      "active": true
    }
  ]
}

【问题讨论】:

    标签: json csv


    【解决方案1】:

    使用python,这可以很容易地完成或几乎完成。也许这段代码会以某种方式帮助您理解这一点。

    import json,csv    
    
    data = []
    
    with open('your_json_file_here.json') as file:
        for line in file:
            data.append(json.loads(line))
    length = len(data)
    
    with open('create_new_file.csv','w') as f:
        writer = csv.writer(f)
        writers = csv.DictWriter(f, fieldnames=['header1','header2'])
        writers.writeheader()
        for iter in range(length):
    
            writer.writerow((data[iter]['specific_col_name1'],data[iter]['specific_col_name2']))
    f.close()
    

    【讨论】:

      猜你喜欢
      • 2020-02-20
      • 1970-01-01
      • 2018-01-07
      • 2020-10-28
      • 1970-01-01
      • 2020-04-02
      • 2021-11-04
      • 2018-10-27
      相关资源
      最近更新 更多