1

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?

Community
  • 1
  • 1

1 Answers1

1

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"}}
Gourav
  • 570
  • 3
  • 16
  • If I want to get json as ---------- {"desc":{"a":"1015.62","a":"1014.08","a":"1012.1","a":"1019.09","a":"1018.9","a":"1019.86","a":"1084.12}------------- not 1,2.... as keys. is this possible inside each function? –  Nov 30 '15 at 11:01
  • tmp_str["desc"]["a"] = x – Gourav Nov 30 '15 at 11:15
  • I triesd that, but it generates only one json element and not all the 6 –  Nov 30 '15 at 11:19
  • But, I need the json in that format. is there any other possible in ruby to gert that? –  Nov 30 '15 at 11:24
  • One possible is for key "a" you can put all the values is that ok – Gourav Nov 30 '15 at 11:27
  • Infact I tried this for other reasons to create a chart. for that I need json like this only. –  Nov 30 '15 at 11:29
  • tmp_str = {} tmp_str["desc"]["a"] = my_arr puts JSON.generate(tmp_str) Output : {"desc":{"a":["1015.62","1014.08","1012.1","1019.09","1018.9","1019.86","1019.84"]}}, loop through it and put the values of a into chart – Gourav Nov 30 '15 at 11:52