为什么json.loads()在某些字符串上起作用? [英] Why does json.loads() work on some strings?

查看:256
本文介绍了为什么json.loads()在某些字符串上起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json1中所示的JSON字符串.我正在尝试将其解析为JSON,但似乎无法正常工作.怎么了?

I've a JSON string like the one shown in json1. I'm trying to parse this as a JSON but it doesnt seem to work. What is going wrong?

import json

string1 = "[]"
list1 = "['hi','bye']"
json1 = "{'genre': ['Action', 'Comedy']}"

print json.loads(string1)
print json.loads(list1)
print json.loads("{'genre': ['Action', 'Comedy']}")

这给了我错误

Traceback (most recent call last):
  File "python", line 8, in <module>
ValueError: No JSON object could be decoded

推荐答案

json需要双引号的字符串,而您有单引号的字符串.您可以使用ast.literal_eval:

json expects double quoted strings, you have single-quoted strings. You can load your strings using ast.literal_eval:

import ast
print(ast.literal_eval("{'genre': ['Action', 'Comedy']}"))

结果:

{'genre': ['Action', 'Comedy']}

这篇关于为什么json.loads()在某些字符串上起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆