从JSON Ruby on Rails获取第一个数组值

时间:2015-09-07 19:03:43

标签: ruby-on-rails arrays json

我从uri调用

返回了这个JSON
[
  "cat",
  [
    "cat",
    "cat tree",
    "cat toys",
    "cat bed",
    "cat litter",
    "cat ears",
    "cat food",
    "catastrophe",
    "caterpillar",
    "catan"
  ],
  [
    {
      "nodes": [
        {"name": "Pet Supplies", "alias": "pets"},
        {"name": "Home & Kitchen", "alias": "garden"},
        {"name": "Women's Clothing", "alias": "fashion-womens-clothing"},
        {"name": "Toys & Games", "alias": "toys-and-games"}
      ]
    },
    {}, {}, {}, {}, {}, {}, {}, {}, {}
  ],
  []
]

我试图在轨道上的红宝石中的第一个“cat”(斜体显示)之后获取数组。我试过了

a= JSON.parse(doc) 
result = a["cat"]

它不起作用。我得到一个奇怪的整数错误。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

 I'm a message on a new line, look at me. New line.

> doc = "..." # the json string > json = JSON.parse(doc) > result = json.detect{|e| e.is_a?(Array)} 现在是:

result

答案 1 :(得分:0)

所有你需要的是:

json = JSON.parse(doc) 
result = json[1]

您的数据结构是一个数组。索引0处的元素是字符串"cat"。索引1处的元素是数组[ "cat", "cat trees", "cat toys", ... ]