3

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.

4
  • \n is not invalid. It is a line feed. Commented Nov 21, 2016 at 18:31
  • 1
    but you can't have it like \n in a python string, because then it is escaped for python, but not for json. You need to write \\n in your string so that it is \n in the json. Commented Nov 21, 2016 at 18:32
  • This isn't a problem with JSON files at all; it's only a problem with JSON strings embedded in Python source code. And if you want to do that for some reason, use raw strings: input = r''' { Commented Nov 21, 2016 at 18:42
  • 1
    input isn't valid json. If you want to copy your json file to a string, try print(repr(open('test.json').read())) and use that. Commented Nov 21, 2016 at 18:43

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Any reason to prefer that vs suggesting that the OP use a raw string when embedding JSON constants as strings (for whatever reason)?
@CharlesDuffy I don't think you can split a raw string over multiple lines like that. He'd need to escape the newlines, and that's no better than having to escape the backslash in \n. Of course, there's no need for the JSON to be on multiple lines.
r''' ... ''' is absolutely valid syntax for multi-line raw strings.
Ahh, didn't realize you could combine the two.
4

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.