繁体   English   中英

我的控制器(Ruby / Rails)中有一个JSON对象,但我想访问Json的Object属性。 怎么做

[英]I have a JSON object in my Controller (Ruby/Rails) but i want to access the Json's Object attributes. How to do that

require 'rubygems'
require 'json'
require 'net/http'
require 'uri'
require 'open-uri'
require 'openssl'

class UsersController < ApplicationController

  def show
    @json_object = JSON.pretty_generate(JSON.parse(open("some link").read))
  end
end

这是我的控制器文件

我创建了一个视图以显示JSON对象的内容。

show.html.erb

<% = @json_object %>

它输出JSON对象,但

1)我想以特定格式打印JSON对象。

2)我想在数据库中保存某些JSON值。

ruby中的JSON对象只是一个HashArrayHashStringNumericArray

因此,要获取json中的特定元素,您应该按照JSON结构的建议简单地找到它:

json_string = '{ "test": { "this": "here" }, "other": 3 }'

@json_object = JSON.parse(json_string)

@json_object['test']['this']
# => "here"

要将其再次打印为JSON对象,您需要使用JSON.pretty_generate对其进行JSON.pretty_generate

JSON.pretty_generate(@json_object['test'])
# => {
# =>   "this": "here"
# => }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM