AmirolAhmad AmirolAhmad - 1 month ago 17
Ruby Question

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?

Answer

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