Turning JSON keys into symbols
I'm really new to the API topic. I've displayed the JSON from API, read a ton of docs and I understand the idea of how to convert JSON keys into ruby symbols but I do not understand how to actually do it. I tried...
1) a way using Faraday.
2) using JSON.parse
3) using symbolize_keys: true
...and other stuff.
What my code looks like now. I also commented what way I tried, so you can see.
class ProductsController < ApplicationController
require 'json'
def index
@products = Product.find(:all) # GET 'http://api.example.com/store/products.json'
products = Faraday.new(:url => 'http://api.example.com') do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
#GET
response = products.get '/store/products.json'
response.body
products.get '/store', { :name => 'Koala' }
# @products = JSON.parse(@products, symbolize_keys: true)
end
end
Output currently is just a JSON string. How can I parse this?
Flowers99.0Guitar10.99Love20.0Penguin500.0Koala1000.0[...]
HTML
= @products.each do |product|
tr
td = product.name
td = product.price
Use symbolize_names
not symbolize_keys
. symbolize_keys
is a Rails method.
Here is how:
JSON.parse(@products, symbolize_names: true)
For more info see:
JSON.parse
ActiveSuport::Hash#symbolize_keys