我有 a = first
这是
=> <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">
所以当我调用a.value
时,它会返回=> "[{"ssid":"LVL6-Staff","password":"987654321","dhcp":"已启用"}]"
然后,我想获取密码的值:
x = JSON.parse(a.value)
x.last['password']
=> "987654321"
我的问题是,在获取密码值后,我想将密码值更新为“123456789”并保存。如何实现?
最佳答案
这应该很简单。
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\"}]"
关于ruby-on-rails - 使用 json.parse 更新哈希数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40481786/