开发者

how to convert string to integer when I try to access the data in json converted to hash in ruby?

开发者 https://www.devze.com 2023-04-06 07:57 出处:网络
I have converted the data in json to a hash and tried to access the data. I used the following code: require \'yajl\'

I have converted the data in json to a hash and tried to access the data. I used the following code:

require 'yajl'
json=File.new('5104.txt', 'r')
parser=Yajl::Parser.new
hash=parser.parse(json)
puts hash['response']['venue']['id']
puts hash['response']['venue']['name']
puts hash['response']['venue']['categories']['parents']

When I run this code, I had this error message says:

test.rb:8:in `[]': can't convert String into Integer (TypeError)
    from test.rb:8:in `<main>'

I assume it means that the data type of 'parents' is string which cannot be converted to开发者_开发技巧 integer. Does anyone know how should I solve this problem? Is there anyway I can convert this string into integer and save it?

Thanks ahead and I really appreciate your help.


Thanks a lot for your answers. Line 8 is the last line for 'parents'. I can use this code to get 'id' and 'name', but cannot get the data for 'parent'. Here is the json;

response: {
     venue: {
        id: "xxx"
        name: "xxx"
        contact: {
           phone: "xxx"
           formattedPhone: "xxx"
           twitter: "theram"
        }
        location: {
           address: "xxx"
           lat: xxx
           lng: xxx
           postalCode: "xxx"
           city: "xxx"
           state: "xxx"
           country: "xxx"
        }
        categories: [
           {
              id: "xxx"
              name: "xxx"
              pluralName: "xxx"
              shortName: "xxx"
              icon: "xxx"
              parents: [
                 "xxx"
              ]
              primary: true
           }
        ]
     }
}

I converted the json to a hash. If it is the case that this json is an array which requires integers for its keys, is there anyway that I can convert this string into an integer so that I can still use this code to get the data I want? If not, is there any other ways that I can get data for 'parents'? Regular expression?

Thanks ahead :)


Categories is an array, you should get an item before trying to get the parents:

hash['response']['venue']['categories'].first['parents']

There's also a primary parameter, if there could be more than one category and want to get the primary one, use Array#select:

hash['response']['venue']['categories'].select {|category| category['primary'] } .first['parents']


Are you absolutely positive that what you're getting out of the JSON is a hash? Because that error message generally means you're trying to access an array with a non-integer key.

I'm guessing that your JSON is actually an array, and ruby is dutifully complaining that you're not treating it like one.

0

精彩评论

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