JSON produced by Ruby not compatable with JavaScript's JSON parser -


i running issue json produced ruby script not compatable when parsed javascripts json.parse. consider following example:

# ruby require 'json' hash = {} hash["key"] = "value \u001a unicode" hash.to_json => '{"key":"value \u001a unicode"}'  // javascript json.parse('{"key":"value \u001a unicode"}') => json.parse: bad control character in string literal @ line 1 column 2 of json data 

the issue unicode character \u001a. solution escape \u001a \\u001a, thing is, \u001a automatically inserted string ruby. can't reliably post-process result. ideas how solve this?

please note wish call json.parse inside javascript execution environment, not inside ruby's interpreter.

the short version you're interpreting string javascript expression before attempting decode json.

u+001a control character. rfc 4627 explicitly disallows control characters u+0000-u+001f in quoted strings. problem here not the json invalid, unescaping control characters before attempting parse them json.

when dump string "\u001a" ruby , copy , paste javascript interpreter, escape sequence translates unescaped control character, not valid character in json! non-prohibited characters work fine - can happily json.parse('["\u0020"]'), example.

however, if don't interpret string javascript, , instead read raw bytes, parse correctly.

$ irb irb(main):001:0> require 'json' => true irb(main):003:0> open("out.json", "w") {|f| f.print json.dump(["\u001a"]) } => nil  $ node -e 'require("fs").readfile("out.json", function(err, data) { console.log(json.parse(data)); });' [ '\u001a' ] 

if you're going copy-pasting, need copying escaped version of string, when string parsed javascript engine, escape double-escaped sequences unescape escape sequences rather characters. so, rather copying output of json.dump(["\u001a"]), should copying output of puts json.dump(["\u001a"]).inspect, correctly escape escape sequences in string.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -