Python 'строковые индексы должны быть целыми числами' при попытке анализа JSON - PullRequest
0 голосов
/ 16 декабря 2018

Когда я пытаюсь прочитать файл json

for index, js in enumerate(json_files):
    with open(os.path.join(path_to_json, js)) as json_file:
        json_text = json.load(json_file)
        t_id = json_text["id"]
        created_at = json_text["created_at"]
        text = json_text["text"]
        user_name = json_text["user"]["name"]
        location = json_text["user"]["location"]
        jsons_data.loc[index] = [t_id,created_at,text,user_name,location]

я получил эту ошибку

TypeError: строковые индексы должны быть целыми числами

это в моем файле json

"{\"created_at\":\"Wed Nov 07 06:01:26 +0000 2018\",\"id\":1060049570195853312,\"id_str\":\"1060049570195853312\",\"text\":\"RT @maulinaantika: Tempe Khot News:\\nDiduga pertemuan kontrak politik antara Polri & timses jokowi tahun 2014\\n\\nDalam foto tersebut terlihat\\u2026\",\"source\":\"\\u003ca href=\\\"https:\\/\\/mobile.twitter.com\\\" rel=\\\"nofollow\\\"\\u003eTwitter Lite\\u003c\\/a\\u003e\",\"truncated\"

когда я попробую вот так

with open('tm.json', 'r') as f:
    for line in f:
        text = line.encode("utf-8")
        json_text = json.loads(text)

print(json_text)

я получу такой результат

{"created_at":"Sat Dec 08 12:58:14 +0000 2018","id":1071388484609413120,...

может кто-нибудь подсказать мне, как решить эту проблему?

1 Ответ

0 голосов
/ 16 декабря 2018

Самое простое объяснение Почему я получаю эту ошибку , учитывая, что ваш код:

json_text = json.load(json_file)

предоставляет вам строку.Что вы пытаетесь использовать как словарь:

 t_id = json_text["id"]
 created_at = json_text["created_at"]
 text = json_text["text"]
 user_name = json_text["user"]["name"]
 location = json_text["user"]["location"] 

Вы можете использовать try: ... except Exception as e: ..., чтобы избежать этого и получить имя вашего json, который является виновником.Затем вы можете исправить свои данные JSON:

for index, js in enumerate(json_files):
    with open(os.path.join(path_to_json, js)) as json_file:
        json_text = json.load(json_file)
        try:
            t_id = json_text["id"]
            created_at = json_text["created_at"]
            text = json_text["text"]
            user_name = json_text["user"]["name"]
            location = json_text["user"]["location"]
            jsons_data.loc[index] = [t_id,created_at,text,user_name,location]
        except TypeError as te:
            print("Bad json - not a dict: ", os.path.join(path_to_json, js))
            print("Json was deserialized into a : ", type(json_text) )
            break # exit while, fix your data, do until it works

См .:

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...