簡體   English   中英

Python Json加載()返回字符串而不是字典?

[英]Python Json loads() returning string instead of dictionary?

我正在嘗試使用 Python 3 的內置 JSON 模塊進行一些簡單的 JSON 解析,並且通過閱讀有關 SO 和谷歌搜索的一堆其他問題,這似乎應該非常簡單。 但是,我認為我得到的是返回的字符串而不是預期的字典。

首先,這是我試圖從中獲取值的 JSON。 這只是 Twitter API 的一些輸出

[{'in_reply_to_status_id_str': None, 'in_reply_to_screen_name': None, 'retweeted':     False, 'in_reply_to_status_id': None, 'contributors': None, 'favorite_count': 0, 'in_reply_to_user_id': None, 'coordinates': None, 'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', 'geo': None, 'retweet_count': 0, 'text': 'Tweeting a url \nhttp://t.co/QDVYv6bV90', 'created_at': 'Mon Sep 01 19:36:25 +0000 2014', 'entities': {'symbols': [], 'user_mentions': [], 'urls': [{'expanded_url': 'http://www.isthereanappthat.com', 'display_url': 'isthereanappthat.com', 'url': 'http://t.co/QDVYv6bV90', 'indices': [16, 38]}], 'hashtags': []}, 'id_str': '506526005943865344', 'in_reply_to_user_id_str': None, 'truncated': False, 'favorited': False, 'lang': 'en', 'possibly_sensitive': False, 'id': 506526005943865344, 'user': {'profile_text_color': '333333', 'time_zone': None, 'entities': {'description': {'urls': []}}, 'url': None, 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'protected': False, 'default_profile_image': True, 'utc_offset': None, 'default_profile': True, 'screen_name': 'KickzWatch', 'follow_request_sent': False, 'following': False, 'profile_background_color': 'C0DEED', 'notifications': False, 'description': '', 'profile_sidebar_border_color': 'C0DEED', 'geo_enabled': False, 'verified': False, 'friends_count': 40, 'created_at': 'Mon Sep 01 16:29:18 +0000 2014', 'is_translator': False, 'profile_sidebar_fill_color': 'DDEEF6', 'statuses_count': 4, 'location': '', 'id_str': '2784389341', 'followers_count': 4, 'favourites_count': 0, 'contributors_enabled': False, 'is_translation_enabled': False, 'lang': 'en', 'profile_image_url': 'http://abs.twimg.com/sticky/default_profile_images/default_profile_6_normal.png', 'profile_image_url_https': 'https://abs.twimg.com/sticky/default_profile_images/default_profile_6_normal.png', 'id': 2784389341, 'profile_use_background_image': True, 'listed_count': 0, 'profile_background_tile': False, 'name': 'Maktub Destiny', 'profile_link_color': '0084B4'}, 'place': None}]

我將此字符串分配給一個名為 json_string 的變量,如下所示:

json_string = json.dumps(output)
jason = json.loads(json_string)

然后,當我嘗試從“jason”字典中獲取特定鍵時:

print(jason['hashtags'])

我收到一個錯誤:

TypeError: string indices must be integers

我希望能夠將 json 輸出轉換為字典,然后使用jason[key_name]調用來使用指定的鍵獲取值。 我在這里有什么明顯的遺漏嗎?

這是我從 Java 畢業后第一次使用 Python。 我非常喜歡這種語言,並認為它非常強大。 因此,非常感謝您對此的任何幫助!

好的,首先您應該打印您的對象,以便您可以閱讀它:

>>> from pprint import pprint
>>> output = [{'in_reply_to_status_id_str': None, 'in_reply_to_screen_name': None, 'retweeted':     False, 'in_reply_to_status_id': None, 'contributors': None, 'favorite_count': 0, 'in_reply_to_user_id': None, 'coordinates': None, 'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', 'geo': None, 'retweet_count': 0, 'text': 'Tweeting a url \nhttp://t.co/QDVYv6bV90', 'created_at': 'Mon Sep 01 19:36:25 +0000 2014', 'entities': {'symbols': [], 'user_mentions': [], 'urls': [{'expanded_url': 'http://www.isthereanappthat.com', 'display_url': 'isthereanappthat.com', 'url': 'http://t.co/QDVYv6bV90', 'indices': [16, 38]}], 'hashtags': []}, 'id_str': '506526005943865344', 'in_reply_to_user_id_str': None, 'truncated': False, 'favorited': False, 'lang': 'en', 'possibly_sensitive': False, 'id': 506526005943865344, 'user': {'profile_text_color': '333333', 'time_zone': None, 'entities': {'description': {'urls': []}}, 'url': None, 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'protected': False, 'default_profile_image': True, 'utc_offset': None, 'default_profile': True, 'screen_name': 'KickzWatch', 'follow_request_sent': False, 'following': False, 'profile_background_color': 'C0DEED', 'notifications': False, 'description': '', 'profile_sidebar_border_color': 'C0DEED', 'geo_enabled': False, 'verified': False, 'friends_count': 40, 'created_at': 'Mon Sep 01 16:29:18 +0000 2014', 'is_translator': False, 'profile_sidebar_fill_color': 'DDEEF6', 'statuses_count': 4, 'location': '', 'id_str': '2784389341', 'followers_count': 4, 'favourites_count': 0, 'contributors_enabled': False, 'is_translation_enabled': False, 'lang': 'en', 'profile_image_url': 'http://abs.twimg.com/sticky/default_profile_images/default_profile_6_normal.png', 'profile_image_url_https': 'https://abs.twimg.com/sticky/default_profile_images/default_profile_6_normal.png', 'id': 2784389341, 'profile_use_background_image': True, 'listed_count': 0, 'profile_background_tile': False, 'name': 'Maktub Destiny', 'profile_link_color': '0084B4'}, 'place': None}]
>>> pprint(output)
[{'contributors': None,
  'coordinates': None,
  'created_at': 'Mon Sep 01 19:36:25 +0000 2014',
  'entities': {'hashtags': [],
               'symbols': [],
               'urls': [{'display_url': 'isthereanappthat.com',
                         'expanded_url': 'http://www.isthereanappthat.com',
                         'indices': [16, 38],
                         'url': 'http://t.co/QDVYv6bV90'}],
               'user_mentions': []},
  'favorite_count': 0,
  'favorited': False,
  'geo': None,
  'id': 506526005943865344,
  'id_str': '506526005943865344',
  'in_reply_to_screen_name': None,
  'in_reply_to_status_id': None,
  'in_reply_to_status_id_str': None,
  'in_reply_to_user_id': None,
  'in_reply_to_user_id_str': None,
  'lang': 'en',
  'place': None,
  'possibly_sensitive': False,
  'retweet_count': 0,
  'retweeted': False,
  'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>',
  'text': 'Tweeting a url \nhttp://t.co/QDVYv6bV90',
  'truncated': False,
  'user': {'contributors_enabled': False,
           'created_at': 'Mon Sep 01 16:29:18 +0000 2014',
           'default_profile': True,
           'default_profile_image': True,
           'description': '',
           'entities': {'description': {'urls': []}},
           'favourites_count': 0,
           'follow_request_sent': False,
           'followers_count': 4,
           'following': False,
           'friends_count': 40,
           'geo_enabled': False,
           'id': 2784389341,
           'id_str': '2784389341',
           'is_translation_enabled': False,
           'is_translator': False,
           'lang': 'en',
           'listed_count': 0,
           'location': '',
           'name': 'Maktub Destiny',
           'notifications': False,
           'profile_background_color': 'C0DEED',
           'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png',
           'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png',
           'profile_background_tile': False,
           'profile_image_url': 'http://abs.twimg.com/sticky/default_profile_images/default_profile_6_normal.png',
           'profile_image_url_https': 'https://abs.twimg.com/sticky/default_profile_images/default_profile_6_normal.png',
           'profile_link_color': '0084B4',
           'profile_sidebar_border_color': 'C0DEED',
           'profile_sidebar_fill_color': 'DDEEF6',
           'profile_text_color': '333333',
           'profile_use_background_image': True,
           'protected': False,
           'screen_name': 'KickzWatch',
           'statuses_count': 4,
           'time_zone': None,
           'url': None,
           'utc_offset': None,
           'verified': False}}]

通過查看這個,您可以看到輸出是一個包含單個dictlist 要訪問它,您需要:

>>> first_elem = output[0]

您還將看到first_elem hashtags包含在鍵entities下的第二級dict中:

>>> entities = first_elem['entities']
>>> pprint(entities)
{'hashtags': [],
 'symbols': [],
 'urls': [{'display_url': 'isthereanappthat.com',
           'expanded_url': 'http://www.isthereanappthat.com',
           'indices': [16, 38],
           'url': 'http://t.co/QDVYv6bV90'}],
 'user_mentions': []}

現在您可以訪問hashtags

>>> entities['hashtags']
[]

這恰好是空列表。

要轉換為 JSON,請注意注釋:

>>> import json
>>> # Make sure output is the list object not a string representing the object
>>> json_string = json.dumps(output)
>>> jason = json.loads(output)
>>> jason[0]['entities']['hashtags']
[]

我認為您的問題是您在json.dumps之前輸出了一個字符串,這意味着json.loads將返回一個字符串,而不是一個 json 對象。

@Dan 的回答是正確的,這不是有效的 JSON。 然而,它是一個有效的 python 字典,我假設你使用 python 從 Twitter 獲得它然后打印它。

首先,您的 JSON 示例不是有效的 JSON; Twitter API 不會輸出這個,因為它會破壞每個符合標准的 JSON 消費者。

  • jsonlint顯示了第一個明顯的語法錯誤:單引號而不是雙引號字符串。
  • 其次,您有None ,其中 JSON 需要nullFalse代替falseTrue代替true

您所謂的“JSON”示例似乎已被預解碼為 Python :)。 當我使用一段真實的 JSON 時,它的工作原理完全符合預期:

import json

json_string = r"""
[{"actual_json_key":"actual_json_value"}]
"""

jason = json.loads(json_string)

print(jason[0]["actual_json_key"])

我做了json.loads(json.loads(string))並且能夠得到字典。 你可以檢查一下。 第一次它不僅返回相同的字符串,而且處理它(例如刪除\\字符)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM