简体   繁体   English

TypeError:字符串索引必须是整数,同时尝试将 json 转换为 csv

[英]TypeError: string indices must be integers, while trying to convert json into csv

I am getting this error upon running the below code运行以下代码时出现此错误

import json
import csv
with open ("sample-json-file.json") as file:
    data = json.load(file)
    
fname = "output.csv"

with open(fname,"w") as file:
    csv_file =csv.writer(file)
    csv_file.writerow(["Name", "Mobile", "Boolean", "Country"])
    for item in data:
        csv_file.writerow([item['name'], item['mobile'], item['boolean'], item['country']])

My json file has the following content-我的 json 文件具有以下内容-

{
   "Name": "Test",
   "Mobile": 12345678,
   "Boolean": "true",
   "Pets": ["Dog", "cat"],
   "country" : "India"
}

Please suggest what changes are to be made, I would be very grateful.请提出要进行哪些更改,我将不胜感激。

Traceback追溯

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-36-9719807e095c> in <module>
      8     csv_file.writerow(["Name", "Mobile", "Boolean", "Country"])
      9     for item in data:
---> 10         csv_file.writerow([item['name'], item['mobile'], item['boolean'], item['country']])

TypeError: string indices must be integers

If the data is a single dict in a file如果数据是文件中的单个dict

  • Given the data in this example鉴于此示例中的数据
  • Using your code as presented使用您提供的代码
  • for item in data: is not needed because you are already writing the keys from data and there is nothing to iterate through. for item in data:不需要,因为您已经从数据中写入键并且没有什么可以迭代的。
with open ("test.json") as file:
    data = json.load(file)
    
fname = "output.csv"

with open(fname,"w") as file:
    csv_file =csv.writer(file)
    csv_file.writerow(["Name", "Mobile", "Boolean", "Country"])
    csv_file.writerow([data['Name'], data['Mobile'], data['Boolean'], data['country']])

If the data is a list of dicts in a file, as follows:如果数据是文件中的dicts list ,如下:

[ {
        "Name": "Test",
        "Mobile": 12345678,
        "Boolean": "true",
        "Pets": ["Dog", "cat"],
        "country": "India"
    }, {
        "Name": "Test",
        "Mobile": 12345678,
        "Boolean": "true",
        "Pets": ["Dog", "cat"],
        "country": "India"
    }]
  • Now for item in data: is needed to loop through each dict in the list现在for item in data:需要遍历列表中的每个dict
with open ("test.json") as file:
    data = json.load(file)

fname = "output.csv"

with open(fname,"w") as file:
    csv_file =csv.writer(file)
    csv_file.writerow(["Name", "Mobile", "Boolean", "Country"])
    for item in data:
        csv_file.writerow([item['Name'], item['Mobile'], item['Boolean'], item['country']])

Your example json is a single dict .您的示例 json 是单个dict When you try to iterate it, you get the dictionary keys (in your case, strings) and of course "name"["name"] isn't a thing.当您尝试迭代它时,您会得到字典键(在您的情况下是字符串),当然"name"["name"]不是一个东西。 You could remove the for loop (its just 1 dict, not a list of dicts) and writerow(data['nmae'], ..) but csv has a DictWriter class you can use instead.您可以删除for循环(它只是 1 个字典,而不是字典列表)和writerow(data['nmae'], ..)csv有一个DictWriter class 您可以使用。

import json
import csv
with open ("sample-json-file.json") as file:
    data = json.load(file)

fname = "output.csv"

fieldnames = ["Name", "Mobile", "Boolean", "Country"]

with open(fname,"w") as file:
    csv_file =csv.DictWriter(file, fieldnames=fieldnames, extrasaction='ignore')
    csv_file.writeheader()
    csv_file.writerow(data)

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

相关问题 TypeError:字符串索引必须是整数 - 在尝试读取秘密时 - TypeError: string indices must be integers - while trying to read secret Python:TypeError:解析JSON时,字符串索引必须为整数 - Python: TypeError: String indices must be integers while parsing JSON 类型错误:解析 json 时字符串索引必须是整数 - TypeError: string indices must be integers while parsing a json 类型错误:使用 Python 解析 JSON 时,字符串索引必须是整数? - TypeError: string indices must be integers while parsing JSON using Python? 尝试将JSON文件转换为CSV时,出现以下错误:TypeError:列表索引必须是整数或切片,而不是str - When trying to convert a JSON file to CSV, I get the following error: TypeError: list indices must be integers or slices, not str TypeError:字符串索引必须是带有.json()字典的整数 - TypeError: string indices must be integers with .json() dictionary TypeError:字符串索引必须是带有JSON的整数 - TypeError: string indices must be integers with JSON TypeError:字符串索引必须是 json 中的整数 - TypeError: string indices must be integers in json 类型错误:字符串索引必须是整数 JSON 文件 - TypeError: string indices must be integers JSON File TypeError:字符串索引必须是flask json的整数 - TypeError: string indices must be integers with flask json
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM