5

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?

Joeyjoejoe
  • 716
  • 2
  • 6
  • 18
  • What are you expecting to happen when you convert a string to JSON format? Don't you need a key->value pair for it to convert properly? – miah Aug 23 '13 at 14:43
  • Well, i was converting to json because, in my program, the content value is sometime a hash, sometime a string or an array... I didn't know their was a problem with the JSON parser and single strings, being given that to_json on string was working. – Joeyjoejoe Aug 23 '13 at 14:49
  • the issue is that JSON works with key value pairs, so `{"content" => "bold text
    italic text"}.to_json` returns valid json, but `"bold text
    italic text".to_json` does not.
    – miah Aug 23 '13 at 15:10

1 Answers1

4

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?

Joeyjoejoe
  • 716
  • 2
  • 6
  • 18