[英]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
This is my controller file 这是我的控制器文件
I have created a view to display the contents of the JSON object. 我创建了一个视图以显示JSON对象的内容。
show.html.erb
<% = @json_object %>
It prints the JSON object but 它输出JSON对象,但
1) I want to print the JSON object in particular format. 1)我想以特定格式打印JSON对象。
2) i want to save certain JSON values in database. 2)我想在数据库中保存某些JSON值。
A JSON object in ruby is simply a Hash
or Array
of Array
s, Hash
es, String
s and Numeric
s. ruby中的JSON对象只是一个Hash
或Array
, Hash
, String
和Numeric
的Array
。
So, to get to a specific element in your json, you should simply find it as the structure of the JSON suggests: 因此,要获取json中的特定元素,您应该按照JSON结构的建议简单地找到它:
json_string = '{ "test": { "this": "here" }, "other": 3 }'
@json_object = JSON.parse(json_string)
@json_object['test']['this']
# => "here"
To print it as a JSON object again, you need to format it using JSON.pretty_generate
: 要将其再次打印为JSON对象,您需要使用JSON.pretty_generate
对其进行JSON.pretty_generate
:
JSON.pretty_generate(@json_object['test'])
# => {
# => "this": "here"
# => }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.