【发布时间】:2021-07-07 10:00:05
【问题描述】:
我有一个带有换行符分隔 json 的文档,我在其中应用了一些功能。一切正常,直到这一行,它看起来就像这样:
{"_id": "5f114", "type": ["Type1", "Type2"], "company": ["5e84734"], "answers": [{"title": " answer 1", "value": false}, {"title": "answer 2
", "value": true}, {"title": "This is a title.", "value": true}, {"title": "This is another title", "value": true}], "audios": [null], "text": {}, "lastUpdate": "2020-07-17T06:24:50.562Z", "title": "This is a question?", "description": "1000 €.", "image": "image.jpg", "__v": 0}
整个代码:
import json
def unimportant_function(d):
d.pop('audios', None)
return {k:v for k,v in d.items() if v != {}}
def parse_ndjson(data):
return [json.loads(l) for l in data.splitlines()]
with open('C:\\path\\the_above_example.json', 'r', encoding="utf8") as handle:
data = handle.read()
dicts = parse_ndjson(data)
for d in dicts:
new_d = unimportant_function(d)
json_string=json.dumps(new_d, ensure_ascii=False)
print(json_string)
错误JSONDecodeError: Unterminated string starting at: line 1 column 260 (char 259) 发生在dicts = parse_ndjson(data)。为什么?我也不知道“答案2”后面的那个符号是什么,它没有出现在数据中,但是当我复制粘贴它时它出现了。
数据有什么问题?
【问题讨论】:
-
您可以尝试将
true更改为True并将false更改为False吗?null到None相同,因为它们是 python 的预期关键字。 -
@JulesCivel 字符串是 JSON,因此它应该是
true而不是True才能成为有效的 JSON。 -
我尝试做
json.loads('<the_JSON>'),它对我有用。我不知道如何重现错误。 -
“我也不知道“答案 2”后面的那个符号是什么”我在您粘贴的内容中没有看到任何不寻常的符号。
-
@KarlKnechtel 使用
json.loads()时,字典包含:{'title': 'answer 2\u2029', 'value': True}。\u2029字符是我认为他在谈论的那个。
标签: python json dictionary parsing