首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字符串转换为用于json处理的原始字符串[Python]

将字符串转换为用于json处理的原始字符串[Python]
EN

Stack Overflow用户
提问于 2021-04-27 19:15:37
回答 1查看 723关注 0票数 0

我有以下代码片段:

代码语言:javascript
复制
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文件,其中包含以下数据:

代码语言:javascript
复制
{
  "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"
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-27 19:24:19

如果您想要创建JSON,您在这里走错了方向。你想要的是dumps而不是loads':

代码语言:javascript
复制
def createJsonText(txt):
    x = {'text': txt}
    y = json.dumps(x)
    open('tone.json','w').write(y)

您的代码有模式=‘a’表示追加,但是一组单独的JSON行不是有效的JSON文件。如果希望它是一个有效的JSON文件,则需要将整个文件作为一个文档。

更新

另一种选择是:

代码语言:javascript
复制
def createJsonText(txt):
    json.dump({'text':txt}, open('tone.json','w'))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67289353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档