Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle \n in json files in python

Tags:

python

json

so I am trying to read a json file like this:

{
      "Name": "hello",
      "Source": " import json \n x= 10, .... "
 }

the way I am trying to read it by using the json library in python thus my code looks something like this:

import json

input =''' {
      "Name": "python code",
      "Source": " import json \n x= 10, .... "
 }'''

output = json.load(input)

print(output)

the problem that source has the invalid character "\n". I don't want to replace \n with \n as this is code will be later run in another program. I know that json.JSONDecoder is able to handle \n but I am not sure how to use.

like image 339
Fernando Peña Avatar asked Dec 06 '25 19:12

Fernando Peña


2 Answers

You need to escape the backslash in the input string, so that it will be taken literally.

import json

input =''' {
      "Name": "python code",
      "Source": " import json \\n x= 10, .... "
 }'''

output = json.loads(input)
print output

Also, you should be using json.loads to parse JSON in a string, json.load is for getting it from a file.

Note that if you're actually getting the JSON from a file or URL, you don't need to worry about this. Backslash only has special meaning to Python when it's in a string literal in the program, not when it's read from somewhere else.

like image 137
Barmar Avatar answered Dec 08 '25 11:12

Barmar


Alternatively, you can define the string in raw format using r:

import json

# note the r
input = r''' {  
      "Name": "python code",
      "Source": " import json \n x= 10, .... "
 }'''
# loads (not load) is used to parse a string
output = json.loads(input)

print(output)
like image 32
Dennis Golomazov Avatar answered Dec 08 '25 11:12

Dennis Golomazov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!