1

I am working in python, and I have a json file that looks like this:

"{\"label\": \"red\", \"seconds\": 20}"
"{\"label\": \"blue\", \"seconds\": 10}"

And I would like to get rid of all backslashes and quotes to look like this:

{label: red, seconds: 20}
 {label: blue, seconds: 10}

I have attached the code to show how I got the json file, which was made from a string of individual json objects.

for value in finalOutputList:
    newOutputString = json.dumps(value)
    finalOutputString += (newOutputString + "\n")

with open('data.json', 'a') as outfile:
    for item in outputString.splitlines():
        json.dump(item, outfile)
        outfile.write("\n")
  • You have to use `json.loads`. – Danizavtz Jun 23 '20 at 22:51
  • 1
    Does this answer your question? [How to parse JSON in Python?](https://stackoverflow.com/questions/7771011/how-to-parse-json-in-python) – Brian McCutchon Jun 23 '20 at 22:55
  • Those do not work, because of the `'\'`. – Trenton McKinney Jun 23 '20 at 22:57
  • 2
    "I have a json file that looks like this"...that's not valid JSON - did you miss some of it out? It's just two strings which have no connection to each other. It would not be decodable as JSON. Anyway it looks like it's been double-encoded at some point. So the solution to that would be to correct the code which made it like that, and not store it in that format to begin with. I see in your code you're using json.dump twice, which is likely the cause of the issue. – ADyson Jun 23 '20 at 22:59
  • 1
    @supercool I did warn you about the object being double encoded in your previous post and I will write you an answer which fixes the way it was written to the file in this question. – Eno Gerguri Jun 23 '20 at 23:03
  • 1
    @supercool I have put up an answer. Does it work for you? – Eno Gerguri Jun 23 '20 at 23:12

1 Answers1

1

PROBLEM: you are double encoding your objects, for example:


for value in finalOutputList:
    newOutputString = json.dumps(value)  # Encoded here with json.dumps
    finalOutputString += (newOutputString + "\n")

with open('data.json', 'a') as outfile:
    for item in outputString.splitlines():
        json.dump(item, outfile). # Encoded once again unnecessarily
        outfile.write("\n")

SOLUTION: remove the double encoding and only encode it once, for example:


for value in finalOutputList:
    newOutputString = json.dumps(value)  # leave this encoding
    finalOutputString += (newOutputString + "\n")

with open('data.json', 'a') as outfile:
    for item in outputString.splitlines():
        outfile.write(item)  # CHANGED to just write the already encoded json string here
        outfile.write("\n")

You switch this to do it the other way round, so you would use json.dumps() when writing to the file and then just leave your finalOutputString, but I recommend the way I just showed you.

Eno Gerguri
  • 639
  • 5
  • 22