如何使用Ruby在JSON数据中实现从访问到哈希的转换?

更新于
2026-10-09 23:28:41
2阅读来源:SEO基础
  • 内容介绍
  • 相关推荐

本文共计348个文字,预计阅读时间需要2分钟。

如何使用Ruby在JSON数据中实现从访问到哈希的转换?

以下是对原文的简化

示例:+json='{posts: [{title: Foobar}, {title: Another}]}'破解:使用 JSON.parse(json)={ posts: [{title: Foobar}, {title: Another}]}但问题在于,我如何实际访问哈希中的数据?我尝试过以下方法:

以下是破解文档中的示例:

json = '{"posts":[{"title":"Foobar"}, {"title":"Another"}]}' Crack::JSON.parse(json) => {"posts"=>[{"title"=>"Foobar"}, {"title"=>"Another"}]}

但是,我如何实际访问哈希中的数据?

我尝试过以下方法:

array = Crack::JSON.parse(json) array["posts"]

array [“posts”]显示所有值,但我尝试了数组[“posts”] [“title”]并且它不起作用.

以下是我要解析的例子:

{"companies"=>[{"city"=>"San Mateo", "name"=>"Jigsaw", "address"=>"777 Mariners Island Blvd Ste 400", "zip"=>"94404-5059", "country"=>"USA", "companyId"=>4427170, "activeContacts"=>168, "graveyarded"=>false, "state"=>"CA"}], "totalHits"=>1}

我想访问公司下的各个元素……比如城市和名字.

像这样?

hash = { "companies" => [ { "city" => "San Mateo", "name" => "Jigsaw", "address" => "777 Mariners Island Blvd Ste 400", "zip" => "94404-5059", "country" => "USA", "companyId" => 4427170, "activeContacts" => 168, "graveyarded" => false, "state" => "CA" } ], "totalHits" => 1 } hash['companies'].each{ |i| puts "city => #{i['city']}" puts "name => #{i['name']}" } # >> city => San Mateo # >> name => Jigsaw hash['companies'][0]['city'] # => "San Mateo" hash['companies'][0]['name'] # => "Jigsaw"

问题是你没有考虑公司指向的阵列.

如何使用Ruby在JSON数据中实现从访问到哈希的转换?

本文共计348个文字,预计阅读时间需要2分钟。

如何使用Ruby在JSON数据中实现从访问到哈希的转换?

以下是对原文的简化

示例:+json='{posts: [{title: Foobar}, {title: Another}]}'破解:使用 JSON.parse(json)={ posts: [{title: Foobar}, {title: Another}]}但问题在于,我如何实际访问哈希中的数据?我尝试过以下方法:

以下是破解文档中的示例:

json = '{"posts":[{"title":"Foobar"}, {"title":"Another"}]}' Crack::JSON.parse(json) => {"posts"=>[{"title"=>"Foobar"}, {"title"=>"Another"}]}

但是,我如何实际访问哈希中的数据?

我尝试过以下方法:

array = Crack::JSON.parse(json) array["posts"]

array [“posts”]显示所有值,但我尝试了数组[“posts”] [“title”]并且它不起作用.

以下是我要解析的例子:

{"companies"=>[{"city"=>"San Mateo", "name"=>"Jigsaw", "address"=>"777 Mariners Island Blvd Ste 400", "zip"=>"94404-5059", "country"=>"USA", "companyId"=>4427170, "activeContacts"=>168, "graveyarded"=>false, "state"=>"CA"}], "totalHits"=>1}

我想访问公司下的各个元素……比如城市和名字.

像这样?

hash = { "companies" => [ { "city" => "San Mateo", "name" => "Jigsaw", "address" => "777 Mariners Island Blvd Ste 400", "zip" => "94404-5059", "country" => "USA", "companyId" => 4427170, "activeContacts" => 168, "graveyarded" => false, "state" => "CA" } ], "totalHits" => 1 } hash['companies'].each{ |i| puts "city => #{i['city']}" puts "name => #{i['name']}" } # >> city => San Mateo # >> name => Jigsaw hash['companies'][0]['city'] # => "San Mateo" hash['companies'][0]['name'] # => "Jigsaw"

问题是你没有考虑公司指向的阵列.

如何使用Ruby在JSON数据中实现从访问到哈希的转换?