我有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":"Enabled"}]"
然后,我想获得密码的值:
x = JSON.parse(a.value)
x.last['password']
=> "987654321"
我的问题是,在获取密码值后,我想将密码值更新为&#39; 123456789&#39;并保存。怎么做到这一点?
答案 0 :(得分:2)
这应该很简单。
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\"}]"
答案 1 :(得分:1)
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"}]
刚刚在irb中测试