无法加载json数据,因为其中的字符串是unicode

问题描述 投票:0回答:2

我有以下json字符串:

{u'debug': {u'version': 3.1}, u'status': u'OK', u'results': {u'api_timestamp': u'1439552208', u'totalCommentsFound': 9300, u'totalCommentsReturned': 25, u'comments': [{u'assetID': 3425398, u'replies': [], u'lft': 9, u'assetURL': u'http://wordplay.blogs.nytimes.com/2015/03/31/why-i-moved-to-florida/', u'parentID': 14580714, u'commentID': 14581040, u'rgt': 10, u'userDisplayName': u'John', u'createDate': u'1427860827', u'userID': 12857582, u'replyCount': 0, u'commentTitle': u'<br/>', u'status': u'approved', u'approveDate': u'1427860868', u'userTitle': u'NULL', u'editorsSelection': 0, u'statusID': 2, u'userURL': u'NULL', u'userLocation': u'Chicago', u'commentType': u'userReply', u'updateDate': u'1427860868', u'commentSequence': 14581040, u'commentBody': u"Yea, Martin, but what does the wife know. She doesn't like It's a Wonderful Life and doesn't even know Bert and Ernie were the cop and the cab driver. She just knows Bert and Ernie as muppets who used to baby sit for her.", u'recommendationCount': 1}, [...]

Full JSON Data File

obj = json.loads(line)

我无法使用json.loads(mystring),因为它会抛出错误。我该怎么办?

python json
2个回答
0
投票

该链接不是JSON而是python dict

您可以使用dumps使其成为有效的JSON字符串:

json_string = json.dumps(your_dict_variable)

然后使用loads使它成为一个字典(它已经是):

json.loads(json_string)


0
投票

这可能有所帮助。我首先从文本中读取原始内容,然后使用literal_evalto将其转换为python字典对象。

演示

import ast
import json
p = "PATH_TO/json_data.txt"
with open(p, "r") as infile:
    data = infile.read()

data = ast.literal_eval(data)
print data['debug']

输出:

{u'version': 3.1}
© www.soinside.com 2019 - 2024. All rights reserved.