【问题标题】:JSON creation for float values in ruby在 ruby​​ 中为浮点值创建 JSON
【发布时间】:2015-11-30 08:48:29
【问题描述】:

我按照这个答案得到了我所期望的 json。

Json creation in ruby for a list

如果我使用该方法,我可以为字符串值生成 json。

假设如果我在数组中有浮点值并遍历它们以生成 json,它不会按预期生成 JSON,它只会生成该数组中的最后一个值,

这是我试过的代码,

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) 

以上代码生成如下json

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

但是我想要json如下,

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

我需要在哪里更改我的代码才能获得这个?

【问题讨论】:

    标签: arrays ruby json


    【解决方案1】:

    你已经很接近了,只需更改以下内容

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

    执行时输出

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

    【讨论】:

    • 如果我想得到 json 为 ---------- {"desc":{"a":"1015.62","a":"1014.08","a" :"1012.1","a":"1019.09","a":"1018.9","a":"1019.86","a":"1084.12}------------- 不是1,2.... 作为键。这可能在每个函数中吗?
    • tmp_str["desc"]["a"] = x
    • 我试过了,但它只生成一个 json 元素而不是全部 6 个
    • 但是,我需要这种格式的 json。红宝石还有其他可能吗?
    • 一种可能是键“a”你可以把所有的值都放好
    猜你喜欢
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    相关资源
    最近更新 更多