Home > other >  Incrementing json value of a key in ruby?
Incrementing json value of a key in ruby?

Time:02-12

I'm looking for a way to increment the values of keys foo and bar

{
  "users": [
    {
      "foo": 6522
    },
    {
      "bar": 20
    }
  ]
}

Here is an example of what I attempted, however the result leaves the values unchanged.

data = JSON.parse(filepath\info.json)

puts data["users"][1].values[0] # 20

data["users"][1].values[0]  = 5

puts data["users"][1].values[0] # remains 20, but expected 25

Is there another way to increment these values?

CodePudding user response:

You'll need to know the key to increment in the user. Since it looks like it's different some times, you can achieve this with 2 eachs

data[:users].each {|u| u.keys.each {|k| u[k]  = 1 } }

Iterate over the users, then iterate over the keys in the user object, adding 1.

This assumes only one key is in users and it's an integer.

values returns a new array so you won't be able to use it that way.

CodePudding user response:

How about:

irb(main):046:1* str = {
irb(main):047:2*   "users": [
irb(main):048:3*     {
irb(main):049:3*       "foo": 6522
irb(main):050:2*     },
irb(main):051:3*     {
irb(main):052:3*       "bar": 20
irb(main):053:2*     }
irb(main):054:1*   ]
irb(main):055:0> }.to_json
=> "{\"users\":[{\"foo\":6522},{\"bar\":20}]}"
irb(main):056:0> json = JSON.parse(str)
=> {"users"=>[{"foo"=>6522}, {"bar"=>20}]}
irb(main):062:0> json['users'][0]['foo']  = 5
=> 6527
irb(main):063:0> json
=> {"users"=>[{"foo"=>6527}, {"bar"=>20}]}
  • Related