Ruby:在现有JSON字符串中集成ruby键/值哈希

时间:2022-10-26 16:23:10

The JSON-String:

jsonString = {"string1" => {"test1" => "test2"}}

results (with JSON.pretty_generate) in a pretty printed:

结果(使用JSON.pretty_generate)打印得很漂亮:

{
    "string1":
    {
        "test1": "test2"
    }
}

But when I try to add all elements of two arrays into this JSON-String

但是当我尝试将两个数组的所有元素添加到此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}}

语法错误,意外'}',期待=> 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.

非常感谢。

1 个解决方案

#1


1  

Try jsonString.merge(my_hash) ?

试试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.

我的理解是,名为jsonString的变量实际上是一个哈希,而不是一个json字符串。如果你想将这个哈希值转换为真正的JSON字符串,你可以导入json模块(使用require'json'),而不是调用jsonStrong.to_json,但是一旦你将哈希值转换为字符串,就很难有其他哈希值。它。最好将所有哈希值一起添加,然后将结果转换为json。

#1


1  

Try jsonString.merge(my_hash) ?

试试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.

我的理解是,名为jsonString的变量实际上是一个哈希,而不是一个json字符串。如果你想将这个哈希值转换为真正的JSON字符串,你可以导入json模块(使用require'json'),而不是调用jsonStrong.to_json,但是一旦你将哈希值转换为字符串,就很难有其他哈希值。它。最好将所有哈希值一起添加,然后将结果转换为json。