简体   繁体   English

如何从 json 文件中提取特定数据并将其保存为 python 文件中的 csv 文件

[英]How to extract specific data from json file and save it as csv file in python

I have imported the following json file " https://pastebin.com/embed_js/PknXEGq2 " and extracted all the products within it, and now i need to print each available product in this particular format: “You can buy Product_Name at our store at Product_Price ”, Product_Name is the product name truncated at 30, and Product_Price is the rounded product price in dd.d format (example: 13.34 ==> 13.3).我已导入以下 json 文件“ https://pastebin.com/embed_js/PknXEGq2 ”并提取其中的所有产品,现在我需要以这种特定格式打印每个可用产品:“您可以在我们的商店购买Product_NameProduct_Price ”中,Product_Name 是在 30 处截断的产品名称,Product_Price 是 dd.d 格式的四舍五入的产品价格(例如:13.34 ==> 13.3)。

  1. if the product is unavailable, it logs the product id and product name如果产品不可用,它会记录产品 ID 和产品名称

  2. if a clue of the product's availability can't be found, it logs an error如果找不到产品可用性的线索,则会记录错误

  3. it saves the available products in a csv file.它将可用产品保存在 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()

assuming your json file looks like:假设您的 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"
      ]
    }
  ]
}

You code could be something like if you needed only name, price and quantity:如果您只需要名称、价格和数量,您的代码可能类似于:

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)

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

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