-2

I'm using 'jbuilder' gem for creating Json. How can I create one Json that look like below

{ranking: {"1-3" => 2,"4-10" => 3, "11-20" => 5 }}

Description for hash

I've some keywords in my db each keyword having its own ranks in google search result. Above json key value pair representing number of keywords in my db that have ranks between 1 to 3, 4 to 10 and 11 to 20.

its easy to crate

{ranking: {"one_to_three" => 2,"four_to_ten" => 3, "eleven_to_twenty" => 5 }}

Using below code.

Jbuilder.new do |ranking|
   ranking.one_to_three 2
   ranking.four_to_ten 3
   ranking.eleven_to_twenty 5
end

But I need to convert this as like

{ranking: {"1-3" => 2,"4-10" => 3, "11-20" => 5 }}

what are the changes i need to be made for above code to achieve this

Please help me

mirajrjaee
  • 19
  • 4
  • Your question is unclear. Both of your JSON examples are not valid JSON. Since the output you want is not valid JSON, the answer to your question how to obtain such output from a JSON library is rather simple: you can't. Period. – Jörg W Mittag Jun 02 '16 at 11:53

1 Answers1

0

The problem with your code is that this

{ranking: {"1-3" => 2,"4-10" => 3, "11-20" => 5 }}

is not a valid JSON use this to validate you JSON

this seems more the definition of a ruby hash using a symbol ranking for the master key and strings "1-3" ... for the second level keys

Here you can know how to build a valid JSON:

http://json.org/

to convert simple JSON hashes is easy to use to_json ant then convert the string using gsub for all and sub for the first instance matching like this

This could be a valid JSON for your structure

{
    "ranking": {
        "1-3": 2,
        "4-10": 3,
        "11-20": 5
    }
}

So let's obtain the last JSON from

irb(main):001:0> require 'json'
=> true
irb(main):002:0> my_hash = {ranking: {"1-3" => 2,"4-10" => 3, "11-20" => 5 }}
=> {:ranking=>{"1-3"=>2, "4-10"=>3, "11-20"=>5}}
irb(main):003:0> string_json = my_hash.to_json
=> "{\"ranking\":{\"1-3\":2,\"4-10\":3,\"11-20\":5}}"
irb(main):005:0> string_json.gsub(":"," => ").sub(" => ", " : ")
=> "{\"ranking\" : {\"1-3\" => 2,\"4-10\" => 3,\"11-20\" => 5}}"

finally to get what you exactly want, play with the ranking word an "

irb(main):037:0> puts string_json.gsub(":"," => ").sub(" => ", ": ").sub("\"ranking\"","ranking")
{ranking: {"1-3" => 2,"4-10" => 3,"11-20" => 5}}
=> nil
anquegi
  • 11,125
  • 4
  • 51
  • 67