Ruby 从 SQL 服务器创建 JSON

Ruby create JSON from SQL Server

我正在尝试根据来自 SQL 服务器 table 的数据在 Ruby 中创建 JSON,基于查询。我和 Ruby 一起工作过很多次,JSON 也有过一些。但是从来没有在一起。

这是我正在尝试创建的 JSON 的示例。

即使仅帮助创建带有嵌套数组和根元素的 JSON 也会有所帮助。

{
  "aaSequences": [
    {
     "authorIds": [
        "ent_fdfdfdfdf_one"
      ],
      "aminoAcids": "aminoAcids_data",
      "name": "bbbbb-22",
      "schemaId": "ls_jgjgjg",
      "registryId": "src_fgfgfgf",
      "namingStrategy": "NEW_IDS"
    },
    {
     "authorIds": [
        "ent_fdfdfdfdf_two"
      ],
      "aminoAcids": "aminoAcids_data",
      "name": "bbbbb-22",
      "schemaId": "ls_jgjgjg",
      "registryId": "src_fgfgfgf",
      "namingStrategy": "NEW_IDS"
    }
  ]
} 

从 Ruby 哈希对象生成 JSON

要生成 json,首先从 Ruby

中的散列(如字典)开始

my_hash = {:foo => 1, :bar => 2, :baz => 3}

确保你也需要 json 包

require 'json'

然后你可以简单地将散列对象转换为JSON字符串

my_hash.to_json # outputs: "{'foo': 1, 'bar': 2, 'baz': 3'}"

您也可以将数组嵌套到散列中

my_hash_2 = {:foo => [1, 2, 3, 4], :bar => ['a', 'b', 'c', 'd']}

我会让你自己尝试一下,但是 ruby 会为你很好地处理嵌套对象。

From the docs