开发者

Consume a JSON feed into proper Ruby

I am currently consuming an api feed into a ruby on rails project. Being new to Ruby I don't feel that I am consuming and managing the JSON properly. There are a few features which are not working and I believe they revolve around how I'm treating the JSON object once I have it. Here is what I am working with.

{ "auth" : {
    "person" : {
        "id" : 1,
        "name" : "john",
        "pass" : "123"
    },
    "person" : {
        "id" : 2,
        "name" : "fred",
        "pass" : "789"
    }
}}

I find I can get a simple array by doing:

jsonArray = JSON.parse(persons)
# the following allows me to target the persons objects
personArray = jsonArray["auth"]["persons"]

The problem here is attempting to do something like personArray.first(5) gives me int to stri开发者_StackOverflowng conversion errors. I'd like to get this into a workable hash, something I can do operations off of, but currently it seems I can only iterate over it as a hash. I may need to sort, pull persons out of, and do other operations to this result data. How should I be correctly importing this?


Actually direct parsing your json string wouldn't give you ["auth"]["persons"]. There is no "persons" field inside the json string......I hope that's a typo error.

The exact format you need in order to make personArray.first(5) to work should be:

{
  "auth": {
    "persons": [ # Note the square bracket here, which defines an array instead of a hash
      {"id": 1, "name": "john", "pass": "123"},
      {"id": 2, "name": "fred", "pass": "789"}
    ]
  }
}

and you could do what you wanted to do now.


Your JSON above results in a JS object storing less data than you think it has. You are overwriting the person key repeatedly. Try copy/pasting this into the console of your web browser:

var o = { "auth" : {
  "person" : {
    "id" : 1,
    "name" : "john",
    "pass" : "123"
  },
  "person" : {
    "id" : 2,
    "name" : "fred",
    "pass" : "789"
  }
}};

JSON.stringify(o);
// '{"auth":{"person":{"id":2,"name":"fred","pass":"789"}}}'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜