Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to_json on single value can't be parse back

i'm trying to implement wysihml5 in a sinatra app using Activerecord.

The rich text editor works great and when i submit the form i got right html post to controller:

pry:> request.params
=> {"title" => "title text",
"content" => "<b>bold text</b><br><i>italic text</i>",
"_wysihtml5_mode" => 1
}

Then, i remove hash entry "_wysihtml5_mode" from request.params to create the db entry, then i convert content to json:

pry:> request.params.delete("_wysihtml5_mode")
=> 1
pry:> request.params["content"].to_json
=> "\"\\u003Cb\\u003Ebold text\\u003C/b\\u003E...
pry:> class.create(request.params)

The problem is i can't get my value back as begining:

pry:> class.last.content
=> "\"\\u003Cb\\u003Ebold text\\u003C/b\\u003E...
pry:> JSON.parse(class.last.content)
JSON::ParseError: 743: unexpected token at '"\\u003Cb\\u003Ebold text\\u003C/b\\u003E...

How could i get back this unicode charcters to their utf-8 style (i might be wrong, i m not comfortable with characters table). It seems that during convertion to json, a " is added at the begining:

                    "<b>bold => "\"\\u003Cb\\u003Ebold

This might be the problem? Any ideas?

like image 419
Joeyjoejoe Avatar asked Oct 04 '22 03:10

Joeyjoejoe


1 Answers

The problem comes from calling to_json on a single value. This doesn't produce a full JSON representation. Here is some examples:

"hello".to_json
=> "\"hello\""

JSON.parse("hello".to_json)
=> JSON::ParseError: 743: unexpected token at...

nil.to_json
=> "null"

JSON.parse(nil.to_json)
=> JSON::ParseError: 743: unexpected token at...

Fortunately, the JSON parser come with a "quirks mode" who allow to parse single values:

"hello".to_json
=> "\"hello\""

JSON.parse("hello".to_json, {:quirks_mode => true})
=> "hello"

nil.to_json
=> "null"

JSON.parse(nil.to_json, {:quirks_mode => true})
=> nil

I'm not sure of what :quirks_mode is really doing, maybe someone could explain it a bit?

like image 72
Joeyjoejoe Avatar answered Oct 10 '22 01:10

Joeyjoejoe