简体   繁体   English

类型错误:使用 Python 解析 Json 时,字符串索引必须是整数错误

[英]TypeError: string indices must be integers error when parsing Json with Python

Before you judge and think to yourself 'I've seen this question a thousand times' please read on and give me a chance, I've scoured the internet for answers but can't seem to find any help.在你判断和思考“我已经看过这个问题一千次”之前,请继续阅读并给我一个机会,我已经在互联网上搜索了答案,但似乎找不到任何帮助。

So I am trying to parse json from an API which I obtain using the following code:所以我试图从我使用以下代码获得的 API 解析 json:

url = 'https://api.companieshouse.gov.uk/company/' + companyno + '/charges'

r = requests.get(url, auth=('API KEY', ''))

data = r.json()

I can get specific values from the json pretty easily, for example using this code:我可以很容易地从 json 中获取特定值,例如使用以下代码:

for each in data['items']:
    print(each['created_on'])

which returns:返回:

2016-11-08
2016-11-08
2016-11-08
2015-03-27
2015-03-27
2015-03-27
2015-03-27
2015-03-27
2007-10-10
2007-09-28
2007-09-19

And this is exactly what I want, it works for other keys to.这正是我想要的,它适用于其他键。

However there is one bit of the json which I just can't seem to access, I have slightly edited the json as to avoid releasing sensitive data (which is available to the public anyway but just to be cautious) but it is largely unchanged:然而,有一点我似乎无法访问的 json,我稍微编辑了 json 以避免发布敏感数据(无论如何都可以向公众提供,但只是要谨慎)但它基本上没有变化:

{  
   'items':[  
      {  
         'created_on':'2016-11-08',
         'etag':'DELETED',
         'classification':{  
            'type':'charge-description',
            'description':'A registered charge'
         },
         'particulars':{  
            'contains_negative_pledge':True,
            'description':'DELETED',
            'type':'brief-description'
         },
         'transactions':[  
            {  
               'links':{  
                  'filing':'DELETED'
               },
               'filing_type':'create-charge-with-deed',
               'delivered_on':'2016-11-21'
            }
         ],
         'links':{  
            'self':'DELETED'
         },
         'charge_code':'DELETED',
         'delivered_on':'2016-11-21',
         'status':'outstanding',
         'persons_entitled':[  
            {  
               'name':'DELETED'
            },
            {  
               'name':'DELETED'
            }
         ],
         'charge_number':59
      },
      {  
         'transactions':[  
            {  
               'delivered_on':'2016-11-10',
               'links':{  
                  'filing':'DELETED'
               },
               'filing_type':'create-charge-with-deed'
            }
         ],
         'particulars':{  
            'contains_negative_pledge':True,
            'contains_fixed_charge':True,
            'floating_charge_covers_all':True,
            'contains_floating_charge':True
         },
         'persons_entitled':[  
            {  
               'name':'DELETED'
            }
         ],
         'charge_number':58,
         'status':'outstanding',
         'charge_code':'DELETED',
         'links':{  
            'self':'DELETED'
         },

It is the [items, links, self] data它是 [items, links, self] 数据

If I use the following code to try and access it:如果我使用以下代码尝试访问它:

for each in data['items']['links']:
    print(each['self'])  

I get the following error:我收到以下错误:

  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str

And if I try to access it using the following code:如果我尝试使用以下代码访问它:

for each in data['items'][0]['links']:
        print(each['self'])

I get this error:我收到此错误:

  File "<stdin>", line 2, in <module>
TypeError: string indices must be integers

I just cant understand why its throwing this error at me, all the other responses on the internet point towards the fact that I am trying to parse a string and not an actual json object but whenever I run the command:我只是不明白为什么它向我抛出这个错误,互联网上的所有其他响应都指向这样一个事实,即我正在尝试解析字符串而不是实际的 json 对象,但是每当我运行命令时:

type(data)

it returns:它返回:

<class 'dict'>

So I know it is a dictionary and that it should be able to iterate through the keys.所以我知道它是一本字典,它应该能够遍历键。

I'm sure I'm making a very stupid mistake and if so I apologize but I just can't figure out what I'm doing wrong, can anyone help?我确定我犯了一个非常愚蠢的错误,如果是这样,我道歉,但我无法弄清楚我做错了什么,有人可以帮忙吗?

ps sorry for the long post. ps 很抱歉发这么长的帖子。

EDIT:编辑:

Thanks so much for all your replies, things seems to make sense now.非常感谢您的回复,现在事情似乎有道理了。 We were all learners at one point!我们曾经都是学习者! :) :)

The 'links' key is pointing to a dictionary value, so iterating over it gives you the key(s) of the dictionary which in this case is 'self' . 'links'键指向一个字典值,所以迭代它会给你字典的键,在这种情况下是'self' You should do:你应该做:

for k, v in data['items'][0]['links'].items():
    if k == 'self':
        print(v)

Or you can simply access the value at key 'self' without iterating:或者您可以简单地访问键'self'处的值而无需迭代:

print(data['items'][0]['links']['self'])

In case there's more than one item in that response, do如果该响应中有多个项目,请执行

for item in data['items']:
    print(item['links']['self'])

otherwise print(data['items'][0]['links']['self']) is sufficient.否则print(data['items'][0]['links']['self'])就足够了。

Alternatively, you could use JSONPath (which is similar to XPath):或者,您可以使用 JSONPath(类似于 XPath):

import jsonpath_rw as jp

for match in jp.parse('items[*].links.self').find(data):
    print(match.value)

data['items'][0]['links']: is a dict: { 'self':'DELETED' } data['items'][0]['links']:是一个字典: { 'self':'DELETED' }

Iterating over a dict yields its keys: in this case, just one, 'self'.迭代一个 dict 会产生它的键:在这种情况下,只有一个,'self'。 `'self'['self'] accounts for your error `'self'['self'] 说明你的错误

What you want is possibly just data['items'][0]['links']['self'] , or iterate over one of the dict methods .keys() , .values() or .items()你想要的可能只是data['items'][0]['links']['self'] ,或者迭代字典方法之一.keys() , .values().items()

for key,value in data['items'][0]['links'].items()
   print(key,":",value)

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

相关问题 python pandas-解析JSON时发生TypeError:字符串索引必须为整数 - python pandas - TypeError when parsing JSON: string indices must be integers Python:TypeError:解析JSON时,字符串索引必须为整数 - Python: TypeError: String indices must be integers while parsing JSON 类型错误:使用 Python 解析 JSON 时,字符串索引必须是整数? - TypeError: string indices must be integers while parsing JSON using Python? 解析 JSON - TypeError:字符串索引必须是整数 - Parsing JSON - TypeError: string indices must be integers TypeError:字符串索引必须是整数 - 解析JSON - TypeError: string indices must be integers - Parsing JSON Python 和 JSON 错误 - TypeError:字符串索引必须是整数 - Python and JSON Error - TypeError: string indices must be integers python和json,错误-TypeError:字符串索引必须为整数 - python and json, Error - TypeError: string indices must be integers TypeError:通过Python读取JSON时,字符串索引必须为整数 - TypeError: string indices must be integers when read JSON via Python TypeError:在 python 中使用 json 文件时,字符串索引必须是整数 - TypeError: string indices must be integers when using json file in python 类型错误:在 Python 中过滤 JSON 中的值时,字符串索引必须是整数 - TypeError: string indices must be integers when filtering values in a JSON in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM