Steve D
Steve D

Reputation: 58

Get first array Values from JSON Ruby on Rails

I have this JSON returned from uri call

[
  "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"}
      ]
    },
    {}, {}, {}, {}, {}, {}, {}, {}, {}
  ],
  []
]

I'm trying to get the array after the first "cat"(showin in italics) in ruby on rails. I've tried

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

and it doesn't work. I get a weird integer error.

Any help would be appreciated.

Upvotes: 1

Views: 3281

Answers (2)

Jordan Running
Jordan Running

Reputation: 106117

All you need is this:

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

Your data structure is an array. The element at index 0 is the string "cat". The element at index 1 is the array [ "cat", "cat trees", "cat toys", ... ].

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19899

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

result is now:

=> ["cat", "cat tree", "cat toys", "cat bed", "cat litter", "cat ears", "cat food", "catastrophe", "caterpillar", "catan"]

Upvotes: 1

Related Questions