Convert JSON into a Hash

skimisha

I have this JSON and I am trying to send it to a Rails API from Postman:

{"object": 
 { 
    "type": "out", 
    "vars": 
    {
      "x": "x", 
      "y": "y"
    }, 
    "values": 
    {
      "ts": "timestamp", 
      "ok": 
      {
        "total": 2, 
        "min": "x", 
        "max": "y"
      }, 
      "error": 
      {
         "total": 2, 
         "error1": "first", 
         "error2": "second"
      }
    }
  }
 }

I need to convert this into a Hash in my model so that I can manipulate it with before_create. Here's what I came with:

object = self.to_json # => converts object to json
object = JSON.parse(object) # => converts json to hash

1st problem: I get this (id=>nil is not relevant since it will be inserted automatically in the database):

 {"id"=>nil, "type"=>"out", "vars"=>{"x"=>"x", "y"=>"y"}, "values"=>{"ts"=>"timestamp", "ok"=>"{\"total\"=>2, \"min\"=>\"x\", \"max\"=>\"y\"}", "error"=>"{\"total\"=>2, \"error1\"=>\"first\", \"error2\"=>\"second\"}"}, "created_at"=>"2015-01-29T15:45:01.329Z", "updated_at"=>"2015-01-29T15:45:01.329Z"}

and when I try to manipulate object["values"]["ok"], Rails sends the error:

unexpected token at '"{\"total\"=\u003e2, \"min\"=\u003e\"x\", \"max\"=\u003e\"y\"}"'

2nd problem: I can only call object["values"], and I want to call it with a symbol, not a string object[:values].

skimisha

Solved my issues using:

object = self.as_json.with_indifferent_access
# => allowing me to use a symbol key instead of a string

ok_vals = object[:values][:ok].as_json.gsub(/\=\>/, ':')
# => allowing to change json string '{"val1"=>"val1", "val2"=>"val2"}' to '{"val1":"val1", "val2":"val2"}'
ok_vals = JSON.parse(ok_vals)
# => which transform json string to hash {val1: "val1", val2: "val2"}

Feel free to make any suggestions to this code. Thanks for the help.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related