Hey guys so I’m trying to construct some json based on a form submission. My json needs to be something like this (truncated for simplicity):
{"id":0,"creditCard":{"address":{"state":"AZ"}}}
Basically I’m trying to do it like this:
json_hash = Hash.new
json_hash["id"] = 0
json_hash["creditCard"]["address"]["state"] = "test"
json_hash.to_json
But its throwing this errror:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
At the 3rd line in the example given (the deeply nested thing). Do ruby hashes work like this? Or are there extra steps I need to take?
Because at the third line you’re evaluating a
json_hash['creditCard']which isnil, then it has no method[].You can build an hash like that using
and it has the given format.
Thats a short syntax, to specify the fact that what you want in
json_hashit’s NOT a single hash. It is an hash which has the value 0 in its"id"key, then in its"creditCard"it stores another hash which contains another hash (i.e.{"state" => "AZ"}) in its"address"key.Look at this pry transcript:
all these values have different
object_idso they are not the same thing, neither property of the same thing.