1

I'm trying to create a json file via shell, however, new lines are now allowed and through an error.

Invalid control character at: line 5 column 26 (char 87) which points to \n

echo '{
    "param1": "asdfasf",
    "param2": "asffad",
    "param3": "asdfsaf",
    "param4": "asdfasf\nasfasfas"
}' | python -m json.tool > test.json

Assuming I'd like to preserve new lines, how can I get this to put a json file?

UPDATE:

I'm thinking it has something to do with strict mode for python's json encoder/decoder.

If strict is False (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including '\t' (tab), '\n', '\r' and '\0'.

https://docs.python.org/2/library/json.html

How can strict mode be set to False from within python -m json.tool?

Raphael Rafatpanah
  • 17,511
  • 22
  • 84
  • 148

2 Answers2

1

Escaping the \ seems to do the trick:

echo  '{
    "param1": "asdfasf",
    "param2": "asffad",
    "param3": "asdfsaf",
    "param4": "asdfasf\\nasfasfas"
}' | python -m json.tool > test.json

It creates valid json:

with open('/home/test.json', 'rU') as f:
    js = json.load(f)
    print(js)
    print(js["param4"])

Output:

{'param1': 'asdfasf', 'param3': 'asdfsaf', 'param2': 'asffad', 'param4': 'asdfasf\nasfasfas'}
asdfasf
asfasfas
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312
1

zsh is replacing \n with a proper carriage return. You could escape it or use heredoc style instead:

python -m json.tool > test.json << EOF
{
"param1": "asdfasf",
"param2": "asffad",
"param3": "asdfsaf",
"param4": "asdfasf\nasfasfas"
}
EOF
Alastair McCormack
  • 25,004
  • 7
  • 71
  • 96