Amirol Ahmad
Amirol Ahmad

Reputation: 542

Update value in hash array with json.parse

I have a = first which is

=> <Ng::EntityConfiguration id: 15881, entity_id: 1, entity_type: "Ng::Company", key: "wpa2.psk", value: "[{"ssid":"LVL6-Staff","password":"987654321", created_at: "2016-11-08 05:13:04", updated_at: "2016-11-08 05:13:04", name: "WIFI/Level 6">

So when i call a.value, it will return => "[{"ssid":"LVL6-Staff","password":"987654321","dhcp":"Enabled"}]"

then, i wanted to get the value for password:

x = JSON.parse(a.value)
x.last['password']
=> "987654321"

my question is, after get the password value, i want to update the password value to '123456789' and save it. How to achieve this?

Upvotes: 1

Views: 781

Answers (2)

0aslam0
0aslam0

Reputation: 1961

irb(main):010:0> v
=> [{:ssid=>"LVL6-Staff", :password=>"987654321", :dhcp=>"Enabled"}]
irb(main):020:0> v[0][:password]
=> "987654321"
irb(main):021:0> v[0][:password] = "123123"
=> "123123"
irb(main):023:0> v
=> [{:ssid=>"LVL6-Staff", :password=>"123123", :dhcp=>"Enabled"}]

Just tested in irb

Upvotes: 1

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

This should be simple.

string = '[{"ssid":"LVL6-Staff","password":"987654321","dhcp":"Enabled"}]'  # your `a.value`
json = JSON.parse(string)
new_password = '123456'       # or whatever
json.first['password'] = new_password
new_string = json.to_json     # "[{\"ssid\":\"LVL6-Staff\",\"password\":\"123456\",\"dhcp\":\"Enabled\"}]"

Upvotes: 2

Related Questions