如何在 Ruby 中创建 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40072448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a JSON object in Ruby
提问by catch22
I am creating a JSON file with Ruby. I need to create the object "companies" within the JSON file.
我正在用 Ruby 创建一个 JSON 文件。我需要在 JSON 文件中创建对象“公司”。
Expected result:
预期结果:
{"companies":[
{\"label\":\"Wayfair \",\"values\":[54]},
{\"label\":\"Move24 \",\"values\":[29]},
{\"label\":\"Auto1 \",\"values\":[23]},
...
]}
What I am getting:
我得到了什么:
[
"{\"label\":\"Wayfair \",\"values\":[54,54]}",
"{\"label\":\"Move24 \",\"values\":[29,29]}",
"{\"label\":\"GetYourGuide \",\"values\":[28,28]}",
"{\"label\":\"Auto1.com \",\"values\":[20,20]}", ...
]
My code:
我的代码:
data_hash = data_hash.map {|k,v| {label: k, values: v}}
companies_json = []
data_hash.each do |hash|
companies_json << hash.to_json
end
File.open('companies.json', 'w') do |f|
f << companies_json
end
采纳答案by Phrogz
The core of your problem is that you are creating an array of JSON strings, instead of an array and then making that JSON. Instead of:
您的问题的核心是您正在创建一个 JSON 字符串数组,而不是一个数组,然后制作该 JSON。代替:
companies_json = []
data_hash.each do |hash|
companies_json << hash.to_json
end
do:
做:
companies = []
data_hash.each do |hash|
companies << hash
end
companies_json = companies.to_json
回答by the Tin Man
@Phrogz has the correct answer. This is to provide a bit more explanation of what's happening:
@Phrogz 有正确的答案。这是为了对正在发生的事情提供更多解释:
require 'json'
foo = {'a' => 1}
foo.to_json # => "{\"a\":1}"
That's what a JSON serialized hash looks like. It's a string containing escaped quotes wrapping the key, with :delimiting the key and value pair. JSON is always an array, "[...]", or a hash, "{...}", and in either case it's a String. That's just what serializing does and how JSON works.
这就是 JSON 序列化哈希的样子。它是一个字符串,其中包含包裹键的转义引号,并:分隔键和值对。JSON 始终是一个数组"[...]"或散列 ,"{...}"无论哪种情况,它都是一个字符串。这就是序列化的作用以及 JSON 的工作原理。
[foo.to_json] # => ["{\"a\":1}"]
[foo.to_json].class # => Array
That's an array containing a JSON serialized hash, which is what you're doing. You can tell it's not serialized correctly because it's an Array, not a String. The surrounding [...]are outsidethe quotes whereas in JSON they're inside the quotes:
这是一个包含 JSON 序列化哈希的数组,这就是您正在做的。您可以判断它没有正确序列化,因为它是一个数组,而不是一个字符串。周围[...]是外面的引号,而在JSON他们是引号内:
[].to_json # => "[]"
{}.to_json # => "{}"
Moving on...
继续...
[foo].to_json # => "[{\"a\":1}]"
[foo].to_json.class # => String
That's a serialized array of hashes. In this case it's a single hash, but it's sufficient for this example. It's a String after serializing, which you can tell because the array [...]is insidethe surrounding quotes.
这是一个序列化的哈希数组。在这种情况下,它是单个散列,但对于本示例来说已经足够了。这是序列化,你可以告诉,因为数组后的String[...]是内部周围引号。
If you really want to understand this stuff I highly recommend reading both the JSON home page, along with Ruby's JSON, YAMLand Psychdocumentation. JSON is nearly a subset of YAML, so knowing YAML and how Psych implements it is reallyhelpful as you move into working with JSON, YAML and the internet.
如果您真的想了解这些内容,我强烈建议您阅读JSON 主页以及 Ruby 的JSON、YAML和Psych文档。JSON 几乎是 YAML 的一个子集,因此当您开始使用 JSON、YAML 和互联网时,了解 YAML 以及 Psych 如何实现它真的很有帮助。
"Fer instance":
“实例”:
json_hash = '{"a":1}'
yaml_hash = "---\na: 1"
require 'yaml'
YAML.load(json_hash) # => {"a"=>1}
YAML.load(yaml_hash) # => {"a"=>1}
Psych.load(json_hash) # => {"a"=>1}
Psych.load(yaml_hash) # => {"a"=>1}
require 'json'
JSON[json_hash] # => {"a"=>1}
JSON[yaml_hash] # => JSON::ParserError: 743: unexpected token at '---\na: 1'
Kinda blows your mind doesn't it?
有点让你大吃一惊,不是吗?

