string使用ast.literal_eval()函数

时间:2018-05-01 00:45:29

标签: json python-3.x api dictionary

我正在尝试使用ast.literal_eval()将字符串转换为字典。我使用网站的API来检索Json格式的数据。当我将数据打印到我的控制台并使用type()函数时,它将其作为字符串返回(但是形成为字典)。我把str写成了一个json文件。它看起来像这样:

{"productId":1200,"productName":"Mox Sapphire","image":"https://6d4be195623157e28848-7697ece4918e0a73861de0eb37d08968.ssl.cf1.rackcdn.com/1200_200w.jpg","categoryId":1,"groupId":7,"url":"http://store.tcgplayer.com/magic/alpha-edition/mox-sapphire","modifiedOn":"2013-05-09T12:13:41.653","productConditions":[{"productConditionId":15346,"name":"Near Mint","language":"English","isFoil":false},{"productConditionId":317018,"name":"Damaged","language":"English","isFoil":false},{"productConditionId":332776,"name":"Moderately Played","language":"English","isFoil":false},{"productConditionId":348534,"name":"Heavily Played","language":"English","isFoil":false},{"productConditionId":364292,"name":"Lightly Played","language":"English","isFoil":false}]}

当我打开文件并在其上运行type()时,它会显示为<class "str">。然后我尝试使用Json文件上的ast.literal_eval()函数将其转换为字典,这是一个字符串,但是得到以下错误:

Traceback (most recent call last):
  File "C:/Users/Jup/PycharmProjects/WebSc/tcg_player.py", line 62, in <module>
    get_card_detail()
  File "C:/Users/Jup/PycharmProjects/WebSc/tcg_player.py", line 59, in get_card_detail
    x = json.loads(f)
  File "C:\Program Files\Python36\lib\json\__init__.py", line 348, in loads
    'not {!r}'.format(s.__class__.__name__))
TypeError: the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'

我确信我遗漏了一些基本的东西。当我使用TextIOWrapper并且它表示字符串时,我不明白它是type()的类型而不是字符串。如果你能帮助我看到我(可能是显而易见的)缺陷,那就太棒了。

0 个答案:

没有答案