Reputation: 39
The JSON-String:
jsonString = {"string1" => {"test1" => "test2"}}
results (with JSON.pretty_generate) in a pretty printed:
{
"string1":
{
"test1": "test2"
}
}
But when I try to add all elements of two arrays into this JSON-String
keys = [:key0, :key1]
values = [:value0, :value1]
my_hash = Hash[keys.zip values]
jsonString = {"string1" => {"test1" => "test2", my_hash}}
I'm always getting a:
syntax error, unexpected '}', expecting => jsonString = {"string1" => {"test1" => "test2", my_hash}}
I would have expected a behavior like this:
jsonString = {"string1" => {"test1" => "test2", keys[0] => values[0], keys[1] => values[1]}}
Output:
{
"string1":
{
"test1": "test2",
"key0": "value0",
"key1": "value1"
}
}
Is there a way to this using the hash-mechanism?
Thanks a lot.
Upvotes: 1
Views: 87
Reputation: 7223
Try jsonString.merge(my_hash)
?
My understanding is that the variable called jsonString
is actually a hash, not a json string. If you wanted to convert that hash to a real JSON string, you could import the json module (using require 'json'
) than call jsonStrong.to_json
, but once you've converted the hash to a string it's more difficult to had other hashes to it. It's best to add all the hashes together, then convert the result to json.
Upvotes: 1