Python 将每个 Json 字符串转换为

Python convert Json string to for each

我正在使用 sheet.get_all_records() 读取带有 gspread 的 google 电子表格,它输出以下内容:

[{"name": "test 0", "name1": "test 1", "name2": "test 2", "name3": "test 3"}, {"name": "test 0", "name1": "test 1", "name2": "test 2", "name3": "test 3"}, {"name": "test 0", "name1": "test 1", "name2": "test 2", "name3": "test 3"}, {"name": "test 0", "name1": "test 1", "name2": "test 2", "name3": "test 3"}]

我喜欢分开处理每一行:

list_of_hashes = sheet.get_all_records()
json_obj = json.dumps(list_of_hashes)
for line in json_obj:
   print (line['name'])
   print (line['name1'])

我收到错误

TypeError: string indices must be integers

好像无法识别 Json

知道如何解决这个问题

下面的修改怎么样?

json.dumps() 用于将 JSON 对象作为字符串检索。我认为,为了修改您的脚本,有以下两种模式。

模式 1:

发件人:

json_obj = json.dumps(list_of_hashes)

收件人:

json_obj = json.loads(json.dumps(list_of_hashes))

模式二:

如果sheet.get_all_records() returns一个JSON对象,可以直接使用返回值进行for循环,如下所示

json_obj = sheet.get_all_records()
for line in json_obj:
   print (line['name'])
   print (line['name1'])

如果我误解了你的问题,我很抱歉。