简体   繁体   中英

convert Javascript Object to a 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 tried using JSON.parse and JSON.load
both of them throw

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

Is there a generic solution or should I use regex and then construct the hash in ruby ?

ruby 1.9 supports hash of this kind which resembles a javascript object

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

to convert this into a ruby hash

 eval(obj)

This is not a JSON. Actually, JSON is not the same as code, could be interpreted by javascript and evaluated to object.

JSON itself allows only static values (no parseInt) and any keys should be quoted as well.

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

Using regexes and such things ain't good. You'd better just format JSON properly.

Ok, if you're not able to modify that input, you may solve a problem for this particular input with following regexpes:

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

but for any variation in input you'll need to add more and more regexpes.

Generally, in order to interpret javascript you need to ... interpret javascript.

This is possible via installing some js Engine, like Rhino or V8 and binding it to Ruby.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM