【发布时间】:2011-08-10 15:10:25
【问题描述】:
我想将 JSON 字符串分解为更小的对象。我有两台服务器,一台作为整个应用程序的 Web 应用接口,另一台是存储库/数据库。
我能够以 JSON 格式从存储库检索信息到网络应用程序,但之后我不知道如何返回它。
以下是返回的 JSON 示例:
{"respPages":[{"page":{"page_url":"http://www.google.com/","created_at":"2011-08-10T11:00:19Z","website_id":1,"updated_at":"2011-08-10T11:00:19Z","id":1}},{"page":{"page_url":"http://www.blank.com/services/content_services/","created_at":"2011-08-10T11:02:46Z","website_id":1,"updated_at":"2011-08-10T11:02:46Z","id":2}}],"respSite":{"website":{"created_at":"2011-08-10T11:00:19Z","website_id":null,"updated_at":"2011-08-10T11:00:19Z","website_url":null,"id":1}},"respElementTypes":[{"element_type":{"created_at":"2011-08-10T11:00:19Z","updated_at":"2011-08-10T11:00:19Z","id":1,"tag_name":"head"}},
JSON中有四个标签:
page
website
elementType
elementData
我想创建四个数组并用匹配这些标签的对象填充它们。
我会想象代码是这样的:
#Get the json from repo using net/http
uri = URI.parse("http://127.0.0.1:3007/repository/infoid/1.json")
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(Net::HTTP::Get.new(uri.request_uri))
@x = response.to_hash
@pages = Array.new
@websites= Array.new
@elementDatas = Array.new
@elementTypes = Array.new
#enter code here`#For every bit of the hash, find out what it is and allocate it accordingly
@x.each_with_index do |e,index|
if e.tagName == pages #Getting real javascripty here. There must be someway to check the tag or title of the element
@pages[index]=e
end
我对返回值的目标是有四个数组,每个数组包含不同类型的对象:
@pagesArray[1]
应包含 JSON 字符串中第一次出现的页面对象。然后对其他人做同样的事情。
当然我需要进一步分解对象,但是一旦我可以分解顶层并对其进行分类,那么我可以更深入。
在 JSON 中已经有标签标题 respPages 和 respWebsites 将所有对象分组。
如何在 Ruby 中将 JSON 转换回对象并使用标签名称之类的名称引用它们?
【问题讨论】:
-
我不明白:你想让json字符串转换成一个对象?如果是这样:
ActiveSupport::JSON.decode(string) -
不完全。我想识别 json 字符串中的对象。字符串是多个对象组合而成,不是单数
-
给出你预期输出的详细例子
-
@apeneadiving。由 json 字符串确定的 4 个充满对象的数组是简短的答案。编辑问题
标签: ruby-on-rails ruby json object hash