JSON创作红宝石的列表 [英] Json creation in ruby for a list

查看:93
本文介绍了JSON创作红宝石的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Ruby。

我要创建一组元素的JSON文件。

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

对于这一点,我使用每个函数来检索DATAS。我想创建JSON为4个长数组如下,

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"
  },
}'

这是我的数组迭代,

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

我知道这里是一个简单的code生成一个JSON,

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)

此语法会生成一个JSON如下,

This syntax will generate a json as follows,

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

但我不知道该怎么做,使JSON我的内容如上所述。谷歌搜索没有给我一个适当的方式做到这一点。

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.

谁能帮助我在这里?

推荐答案

这意味着这个?:

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) 

您可以遍历字符串数组,然后坐字符串哈希object.JSON可以轻松解析哈希objcect。

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

这篇关于JSON创作红宝石的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆