0

I have the following code snippet:

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()

When I execute the aforementioned code I get the following error:

File "hashtag-analyzer.py", line X, in readJson createJsonText(input) File "hashtag-analyzer.py", line Y, in createJsonText y = json.loads(x) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/init.py", line 354, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 4194 (char 4193)

How to resolve this?

Expected output is a json file with name, "tone.json" and the following data inside:

{
  "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"
}
3
  • What is your expected output? Can you edit your question and put it there? Commented Apr 27, 2021 at 19:19
  • Don't use input as a variable, it is a function in python, this can cause some bugs. Commented Apr 27, 2021 at 19:20
  • @AndrejKesely I have updated the question with output value. Commented Apr 27, 2021 at 19:21

1 Answer 1

2

You're going the wrong direction here, if you want to create JSON. You want dumps, not loads':

def createJsonText(txt):
    x = {'text': txt}
    y = json.dumps(x)
    open('tone.json','w').write(y)

Your code had mode='a' for append, but a set of separate JSON lines is NOT a valid JSON file. If you want it to be a valid JSON file, you need the whole file to be one document.

Update

Alternatively:

def createJsonText(txt):
    json.dump({'text':txt}, open('tone.json','w'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.