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.
show.html.erb
<% = @json_object %>
It prints the JSON object but
1) I want to print the JSON object in particular format.
2) i want to save certain JSON values in database.
A JSON object in ruby is simply a Hash
or Array
of Array
s, Hash
es, String
s and Numeric
s.
So, to get to a specific element in your json, you should simply find it as the structure of the JSON suggests:
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.pretty_generate(@json_object['test'])
# => {
# => "this": "here"
# => }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.