Convert Javascript Object to Ruby Hash

I have a javascript object of this form

 obj = "[
   {
     title: "Sean Kingston1",
     duration: parseInt("71", 10),
   },
   {
     title: "Sean Kingston2",
     duration: parseInt("71", 10),
   },
 ]"

      

Is there a way to convert this to a ruby ​​hash?

I have tried using JSON.parse and JSON.load
both they throw

 JSON::ParserError: lexical error: invalid string in json text.
                               {   title: "Sean Kingston1
                 (right here) ------^

      

Is there a general solution or should I use a regex and then build a hash in ruby?

+3


source to share


2 answers


ruby 1.9 supports a hash of this type, which is like a javascript object

 obj = "[
  {
   title: "Sean Kingston1",
   duration: "71",
  },
  {
   title: "Sean Kingston2",
   duration: "71",
  },
 ]"

      



to convert this to ruby ​​hash

 eval(obj)

      

0


source


This is not JSON. Actually JSON is not the same code, can be interpreted by javascript and evaluated for an object.

JSON itself allows you to specify only static values ​​(without parseInt), as well as any keys.

[{
    "title": "Sean Kingston1",
    "duration": 71
 },
 {
    "title": "Sean Kingston2",
    "duration": 71
 }]

      

Using regex and stuff like that is not good. You are better off just formatting JSON.

Ok, if you can't change this input, you can solve the problem for that specific input with the following regexpes:



/^\s*(\w+)\s*:/, '"\1":';
/:\s*parseInt\("(\d+)"\,\s*10)/, ': \1';

      

but for any change in the input, you need to add more and more regular expressions.

Typically, to interpret javascript, you need ... interpret javascript.

This is possible by installing a js Engine like Rhino or V8 and linking it to Ruby.

+1


source







All Articles