我有以下代码片段:
input = "You can check it out here. https://www.youtube.com/watch?v=Ay1gCPAUnxo&t=83s I'll send $20 in bitclout to the first 50 people that follow instructions at end of the video. This is revolutionary. Let's hope it works! <3Building it. What's up y'all"
def createJsonText(input):
input = r'{}'.format(input)
x = r'{ "text":"' + input + r'"}'
print(x)
# parse x as json
y = json.loads(x)
f = open("tone.json", "a")
f.write(str(y))
f.close()当我执行上述代码时,会得到以下错误:
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/init.py",文件"hashtag-analyzer.py",第X行,在readJson createJsonText (输入)文件“hashtag-Analyzer.py”中,第Y行,在createJsonText y= json.loads(x)文件第354行中,在加载返回_default_decoder.decode(s)文件"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py",第339行中,在解码obj中,end = self.raw_decode(s,idx=_w(s,0).end().end()文件第355行,在raw_decode obj中,end = self.scan_once(s,idx) json.decoder.JSONDecodeError: end ',‘分隔符:第1列4194 (char 4193)
如何解决这个问题?
预期输出是一个名为"tone.json“的json文件,其中包含以下数据:
{
"text": "You can check it out here. https://www.youtube.com/watch?v=Ay1gCPAUnxo&t=83s I'll send $20 in bitclout to the first 50 people that follow instructions at end of the video. This is revolutionary. Let's hope it works! <3Building it. What's up y'all"
}发布于 2021-04-27 19:24:19
如果您想要创建JSON,您在这里走错了方向。你想要的是dumps而不是loads':
def createJsonText(txt):
x = {'text': txt}
y = json.dumps(x)
open('tone.json','w').write(y)您的代码有模式=‘a’表示追加,但是一组单独的JSON行不是有效的JSON文件。如果希望它是一个有效的JSON文件,则需要将整个文件作为一个文档。
更新
另一种选择是:
def createJsonText(txt):
json.dump({'text':txt}, open('tone.json','w'))https://stackoverflow.com/questions/67289353
复制相似问题