在Ruby中编辑JSON数组的内容 [英] Editing JSON Array contents in Ruby

查看:326
本文介绍了在Ruby中编辑JSON数组的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON数组的结构是这样的:

  {数据:[{克里斯:[{长:10,纬度:19}]},{斯科特:[{长 :9,纬度:18}]}]}

在Ruby程序,我希望能够为名称编辑lat和长值。但我不太清楚怎么做。

  sections.each做| user_coords |
        user_coords.each做|用户,COORDS |
            如果用户== Usrname然后
                对于Usrname #Change纬度和长期价值
            结束
        结束
结束

如何才能做到这一点?


解决方案

这是如何访问单个元素在你的JSON:

 要求'JSON'富= JSON ['{数据:[{克里斯:[{长:10,纬度:19}]},{斯科特:[{长:9,纬度: 18}]}]}']
富['数据'] [0] ['克里斯'] [0] ['长'] = 5
富['数据'] [0] ['克里斯'] [0] ['纬度'] = 7
富#=> {数据=> [{克里斯=> [{长=> 5,纬度=> 7}]},{斯科特=> [{长=&GT 9,纬度=> 18}]}]}

您可以在一定程度简化了路径,通过使用一个变量作为一个占位符到对象:

 富= JSON ['{数据:[{克里斯:[{长:10,纬度:19}]},{斯科特: [{长:9,纬度:18}]}]}']
克里斯= foo的['数据'] [0] ['克里斯'] [0]
克里斯['长'] = 5
克里斯['纬度'] = 7
富#=> {数据=> [{克里斯=> [{长=> 5,纬度=> 7}]},{斯科特=> [{长=&GT 9,纬度=> 18}]}]}

克里斯指向克里斯的哈希,这是嵌入散里面。更改克里斯散内发生

如果散了通常定义,它会更清洁/清晰简单:

 富= JSON ['{数据:{克里斯:{长:5,纬度:7},斯科特:{长: 9,纬度:18}}}']
富['数据'] ['克里斯'] ['长'] = 5
富['数据'] ['克里斯'] ['纬度'] = 7
富#=> {数据=> {克里斯=> {长=> 5,纬度=> 7},斯科特=> {长=> 9,纬度 = GT; 18}}}

更明确地定义为:

 富= {
  '数据'=> {
    克里斯'= GT; {'长'=> 5,'纬度'=> 7},
    斯科特'= GT; {'长'=> 9,'纬度'=> 18}
  }
}

有条件地遍历哈希查找特定的键/值对看起来像这样与你的哈希:

 要求'JSON'富= JSON ['{数据:[{克里斯:[{长:10,纬度:19}]},{斯科特:[{长:9,纬度: 18}]}]}']USER_NAME ='克里斯'
数据= foo的['数据'。第一
data.first.each做|键,值|
  如果key == USER_NAME
    数据[USER_NAME]。首先['长'] = 5
    数据[USER_NAME]。首先['纬度'] = 6
  结束
结束富#=> {数据=> [{克里斯=> [{长=> 5,纬度=> 6}]},{斯科特=> [{长=&GT 9,纬度=> 18}]}]}

不必使用第一(或 [0] )的哈希元素得到已闻到它。

使用的是正确定义的哈希导致code,看起来像:

 富= JSON ['{数据:{克里斯:{长:10,纬度:19},斯科特:{长: 9,纬度:18}}}']
富['数据']每做|。键,值|
  如果key == USER_NAME
    值['长'] = 5
    值['纬度'] = 7
  结束
结束
富#=> {数据=> {克里斯=> {长=> 5,纬度=> 7},斯科特=> {长=> 9,纬度 = GT; 18}}}



  

我如何添加另一个叫鲍勃人长= 10,纬度= 20


这听起来像你没有操纵/访问哈希值,或如何转换到/从JSON把握好。你会做得很好,得到这些基本下跌。

不要用JSON开始,而是开始与Ruby的哈希值:

 要求'JSON'富= {
  数据=> {
    克里斯=> {
      长=> 5,
      纬度=> 7
    },
    斯科特=> {
      长=> 9,
      纬度=> 18
    }
  }
}

添加到您想要的任何其他哈希元素:

  bob_hash = {'鲍勃'=> {'长'=> 10'纬度'=> 20}}
富['数据']。合并!(bob_hash)

合并! 增加 bob_hash 富['数据'] 。然后,告诉散列输出的JSON重新presentation使用 to_json 。这是一个更容易与熟悉的红宝石结构的工作,并让红宝石做转换成JSON,比它尝试做在现有的JSON字符串字符串处理的繁重工作。如果你有JSON,然后解析它并转换/修改所产生的Ruby对象,然后输出JSON一次。

 提出foo.to_json
#>> {数据:{克里斯:{长:5,纬度:7},斯科特:{长:9,纬度:18},鲍勃:{长 :10,纬度:20}}}

我建议你阅读红宝石JSON哈希,搜索和amp;转换值也,因为它是在生成的散列值,访问一个有用的替代。

My JSON array is structured like this:

{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}

In the ruby program, I am wanting to be able to edit the lat and long values for the names. But I am not quite sure how to do so.

sections.each do |user_coords|
        user_coords.each do |user, coords|
            if user == Usrname then
                #Change lat and long value for Usrname
            end
        end
end

How can this be done?

解决方案

This is how to access individual elements in your JSON:

require 'json'

foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']
foo['data'][0]['Chris'][0]['long'] = 5
foo['data'][0]['Chris'][0]['lat'] = 7
foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>7}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}

You can simplify the path somewhat, by using a variable as a placeholder into the object:

foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']
chris = foo['data'][0]['Chris'][0]
chris['long'] = 5
chris['lat'] = 7
foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>7}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}

chris points to the "Chris" hash, which is embedded inside the foo hash. Changes to the chris hash occur inside foo.

If the hash was defined normally, it'd be more clean/clear and straightforward:

foo = JSON['{"data":{"Chris":{"long":5,"lat":7},"Scott":{"long":9,"lat":18}}}']
foo['data']['Chris']['long'] = 5
foo['data']['Chris']['lat'] = 7
foo # => {"data"=>{"Chris"=>{"long"=>5, "lat"=>7}, "Scott"=>{"long"=>9, "lat"=>18}}}

foo is more clearly defined as:

foo = {
  'data' => {
    'Chris' => {'long' => 5, 'lat' => 7},
    'Scott' => {'long' => 9, 'lat' => 18}
  }
}

Conditionally iterating over the hash to find a particular key/value pair looks like this with your hash:

require 'json'

foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']

user_name = 'Chris'
data = foo['data'].first
data.first.each do |key, value|
  if key == user_name
    data[user_name].first['long'] = 5
    data[user_name].first['lat'] = 6
  end
end

foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>6}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}

Having to use first (or [0]) to get at hash elements has smell to it.

Using a hash that is defined correctly results in code that looks like:

foo = JSON['{"data":{"Chris":{"long":10,"lat":19},"Scott":{"long":9,"lat":18}}}']
foo['data'].each do |key, value| 
  if key == user_name
    value['long'] = 5
    value['lat'] = 7
  end
end
foo # => {"data"=>{"Chris"=>{"long"=>5, "lat"=>7}, "Scott"=>{"long"=>9, "lat"=>18}}}


How can I add another person called Bob with long = 10 and lat = 20

It sounds like you don't have a good grasp of manipulating/accessing hashes, or how to convert to/from JSON. You'd do well to get those basics down.

Don't start with JSON, instead, start with a Ruby hash:

require 'json'

foo = {
  "data" => {
    "Chris" => {
      "long" => 5, 
      "lat" => 7
    }, 
    "Scott" => {
      "long" => 9,
      "lat" => 18
    }
  }
}

Add to that any other hash elements you want:

bob_hash = {'Bob' => {'long' => 10, 'lat' => 20}}
foo['data'].merge!(bob_hash)

merge! adds bob_hash to foo['data']. Then, tell the hash to output its JSON representation using to_json. It's a lot easier to work with familiar Ruby structures, and let Ruby do the heavy-lifting of converting to JSON, than it is to try to do string manipulation on an existing JSON string. If you have the JSON, then parse it and convert/modify the resulting Ruby object, then output the JSON again.

puts foo.to_json
# >> {"data":{"Chris":{"long":5,"lat":7},"Scott":{"long":9,"lat":18},"Bob":{"long":10,"lat":20}}}

I'd recommend reading "Ruby JSON to hash, search & change value" also, as it's a useful alternative for accessing values in the resulting hash.

这篇关于在Ruby中编辑JSON数组的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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