如何使用ruby语言在哈希中添加键/值对

时间:2014-04-01 14:38:24

标签: ruby json

我正在使用ruby 2.0.0,目前我有一个带有以下哈希值的demo.json文件:

{
   "users": 
   {
      "@jon" : 
      {
        "name": "pradeep",
        "Email": "pradeep@yahoo.com",
        "area": "@jon",
        "location": "@newyork"
      },

      "@smith" : 
     {
      "name": "Smith",
      "Email": "Joe@yahoo.com",
      "area": "@smith",
      "location": "@lverginia"
     }
  }
}

现在我使用以下代码在对象中获取json值:

require 'json'
json = File.read('demo.json')
obj = JSON.parse(json)

这里@jon和@smith是用户名,现在我想通过键盘输入获取用户名,而不是@jon中使用相同键盘的所有其他值。

假设我有一个新用户@david,而他的其他值如下:

    "name": "pradeep",
    "Email": "pradeep@yahoo.com",
    "area": "@jon",
    "location": "@newyork"

我想在上面的demo.json文件中添加这个而不删除其他值,不知道我该怎么办?

我试图用这种方式做到这一点:

obj["users"]

但是因为我通过输入获得了用户名,所以在用户密钥输入" obj"之后我就无法使用硬编码用户名。对象,希望这有意义..

1 个答案:

答案 0 :(得分:2)

也请阅读此JSON

我做如下:

require 'json'

json = JSON.parse(File.read("test.json"))

new_information_arry = ["users", "name", "Email", "area", "location"].map do |elem|
   puts "please give the value of #{elem}"
   [elem,gets.chomp]
end

new_information_hash = Hash[new_information_arry[1..-1]]
json['users'][new_information_arry.first.last] = new_information_hash 

File.write("outputfile.json",JSON.pretty_generate(json))

我将以下内容放入我的文件'test.json'

{
   "users": 
   {
      "@jon" : 
      {
        "name": "pradeep",
        "Email": "pradeep@yahoo.com",
        "area": "@jon",
        "location": "@newyork"
      },

      "@smith" : 
     {
      "name": "Smith",
      "Email": "Joe@yahoo.com",
      "area": "@smith",
      "location": "@lverginia"
     }
  }
}

然后我运行上面的代码如下:

please give the value of users
@david
please give the value of name
pradeep
please give the value of Email
pradeep@yahoo.com
please give the value of area
@jon
please give the value of location
@newyor

现在我的输出文件outputfile.json包含:

{
  "users": {
    "@jon": {
      "name": "pradeep",
      "Email": "pradeep@yahoo.com",
      "area": "@jon",
      "location": "@newyork"
    },
    "@smith": {
      "name": "Smith",
      "Email": "Joe@yahoo.com",
      "area": "@smith",
      "location": "@lverginia"
    },
    "@david": {
      "name": "pradeep",
      "Email": "pradeep@yahoo.com",
      "area": "@jon",
      "location": "@newyor"
    }
  }
}