【问题标题】:How to extract specific data from json file and save it as csv file in python如何从json文件中提取特定数据并将其保存为python中的csv文件
【发布时间】:2020-07-25 21:44:38
【问题描述】:

我已导入以下 json 文件“https://pastebin.com/embed_js/PknXEGq2”并提取其中的所有产品,现在我需要以这种特定格式打印每个可用的产品:“您可以在以下位置购买 Product_Name our store at Product_Price”,Product_Name 是被截断为 30 的产品名称,Product_Price 是 dd.d 格式的四舍五入的产品价格(例如:13.34 ==> 13.3)。

  1. 如果产品不可用,它会记录产品 ID 和产品名称

  2. 如果找不到产品可用性的线索,则会记录错误

  3. 它将可用产品保存在 csv 文件中。

     import json
     data = json.load(open('data.json'))
     save_data = []
    
     def get_products():
     query_access = data['Bundles']
     for question_data in query_access:
        save_data.append(question_data)
        print(save_data)
    
    
     get_products()
    

【问题讨论】:

  • 首先,我认为你应该import csv

标签: python json python-3.x csv


【解决方案1】:

假设您的 json 文件如下所示:

{
  "my_data": [
    {
      "name": "Garlic",
      "price": 2.2
    },
    {
      "name": "Potatoes",
      "price": 7.1,
      "quality": "Decent"
    },
    {
      "name": "Tomatoes",
      "price": 6.9,
      "avaiable": "No"
    }
  ],
  "useless_data": [
    {
      "some": "useless",
      "data": [
        "here"
      ]
    }
  ]
}

如果您只需要名称、价格和数量,您的代码可能类似于:

import json
import csv

data = json.load(open("MyBeautifulFile.json"))["my_data"]
useful_columns = ["name", "price", "quality"]
default_value = ""

with open('MyBeautifulFile.csv', mode='w') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=useful_columns)
    writer.writeheader()


    for obj in data:
        row = {}
        for column in useful_columns:
            if column in obj.keys():
                row[column] = obj[column]
            else:
                row[column] = default_value
        writer.writerow(row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-11
    • 2021-10-15
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2019-09-04
    • 2019-09-20
    相关资源
    最近更新 更多