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值。
答案 0 :(得分:1)
ruby中的JSON对象只是Hash
或Array
Array
s,Hash
es,String
和Numeric
s
因此,要获取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_object['test'])
# => {
# => "this": "here"
# => }