0

I am new to Ruby.

I want to create a JSON file for a group of elements.

For this, I am using eachfunction to retrieve the datas. I want to create json as follows for the 4 length array,

'{   
  "desc":{  
    "1":"1st Value",
    "2":"2nd value"
    "3":"3rd Value",
    "4":"4th value"
  },
}'

This is my array iteration,

REXML::XPath.each( doc, "//time" ) { |element1|  
  puts element1.get_text  
}

I know here is the simple code to generate a JSON,

require 'json/add/core'

class Item < Struct.new(:id, :name); end

chair = Item.new(1, 'chair')
puts JSON.pretty_generate(chair)

This syntax will generate a json as follows,

{
  "json_class": "Item",
  "v": [
    1,
    "chair"
  ]
}

But I'm not sure how to do that to make JSON for my elements as stated above. Google search didn't give me a proper way to do this.

Can anyone help me here?

Tobias
  • 4,523
  • 2
  • 20
  • 40
  • It is not clear : from which data do you want to create a JSON output ? And what specific JSON output do you want ? – charlysisto Nov 27 '15 at 11:40
  • Your first JSON code isn't valid! First of all there is a comma missing after the `2nd value` and secondly there is a comma to much at the end of the `desc` hash. Please check your JSON with [JSONLint](http://jsonlint.com/) before you post it. – Tobias Nov 27 '15 at 19:08

1 Answers1

0

it means this?:

require 'json'

my_arr= ["1st Value","2nd Value","3rd Value","4th Value"]

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

my_arr.each do |x|
    tmp_str["desc"]["#{x[0]}"] = x 
end
puts JSON.generate(tmp_str) 

you can iterate the string array ,then take the strings to hash object.JSON can easy to parse Hash objcect .

Clink
  • 1
  • 3