json - Do not interpolate newline characters in curl response in strings -


i'm having bit of difficulty understanding how not interpolate escape characters in strings ... particularly returned curl response. fetching data looks like:

{"foo":"bar\r\nbaz"} 

on own, curl resource print out above no problem. however, if use command substitution in echo $(curl resource), emit:

{"foo":"bar baz"} 

i trying use node parse json in:

node -e "console.log(json.parse('$(curl resource)'))" 

however chokes on interpolated newline characters should because these not valid in json.

i've tried:

node -e $'console.log(json.parse(\'$(curl resource)\'))' # shell syntax error on second `$` node -e $'console.log(json.parse(\''$(curl resource)$'\'))' # fails parse json due newline 

how can prevent command substitution interpolating escape characters.


as echo problem:

echo in zsh default does expand backslash escape sequences such \n, posix prescribes (but note zsh in general deviates posix).

contrast bash, , ksh (depending on underlying /bin/echo utility's behavior), default not (there need use nonstandard -e option turn on such expansion).

thus, to print string as is, portable approach use printf '%s\n' instead of echo, guarantees backslash escape sequences treated literals:

printf '%s\n' "$(curl resource)" 

as alternative works in zsh , bash, can use

echo -e "$(curl resource)" 

as node -e problem:

you must escape \ instances in curl's output prevent them being interpreted backslash escape sequences node:

node -e "console.log(json.parse('$(curl resource | sed 's/\\/\\\\/g')'))"      

if want avoid escaping, pass curl command's output via stdin:

curl resource |    node -e 'console.log(json.parse(require("fs").readfilesync("/dev/stdin", "utf-8")))' 

Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -