user5520878
user5520878

Reputation:

JSON creation for float values in ruby

I followed this answer to get the json as I expected.

Json creation in ruby for a list

If I used that method I am able to generate json for string values.

Suppose if I have float values in array and iterate over them to produce the json, it wont generate JSON as expected, it generates only the last value in that array,

Here is the code I tried,

my_arr = ["1015.62","1014.08","1012.1","1019.09","1018.9","1019.86","1019.84"]

tmp_str = {} 
tmp_str["desc"] = {}

my_arr.each do |x|
    tmp_str["desc"]["#{x[0]}"] = x
    puts 'array'
end

puts JSON.generate(tmp_str) 

The above code generates the following json

{"desc":{"1":"1019.84"}}

But I want to have the json as follows,

{"desc":{"1":"1015.62","2":"1014.08","3":"1012.1","4":"1019.09","5":"1018.9","6":"1019.86","7":"1019.84"}}

Where I need to change my code to get this?

Upvotes: 1

Views: 65

Answers (1)

Gourav
Gourav

Reputation: 576

You were close just change the following

my_arr.each_with_index do |x,i|
   tmp_str["desc"]["#{i+1}"] = x
end

Output when you do

puts JSON.generate(tmp_str)

{"desc":{"1":"1015.62","2":"1014.08","3":"1012.1","4":"1019.09","5":"1018.9","6":"1019.86","7":"1019.84"}}

Upvotes: 1

Related Questions