新手问题 字符串数组转换

easonlovewan · August 31, 2015 · Last by easonlovewan replied at August 31, 2015 · 1869 hits

有这样一个需求:

str = "{\"users\":[{\"id\":1010,\"username\":\"pt_test_15\",\"email\":\"[email protected]\"},{\"id\":1011,\"username\":\"pt_test_16\",\"email\":\"[email protected]\"},{\"id\":1022,\"username\":\"pt_test_27\",\"email\":\"[email protected]\"},{\"id\":1039,\"username\":\"pt_test_44\",\"email\":\"[email protected]\"},{\"id\":1059,\"username\":\"pt_test_63\",\"email\":\"[email protected]\"},{\"id\":1069,\"username\":\"pt_test_72\",\"email\":\"[email protected]\"},{\"id\":1080,\"username\":\"sp9255\",\"email\":\"[email protected]\"},{\"id\":1094,\"username\":\"peter\",\"email\":\"[email protected]\"},{\"id\":1111,\"username\":\"seekingalpha\",\"email\":\"[email protected]\"},{\"id\":1138,\"username\":\"peterchen\",\"email\":\"[email protected]\"}],\"term\":\"p\"}"

现要将 str 转换成一个数组,数组里边儿有五个 hash 格式如下(取五个):

[{:id=>1010,
  :username=>"pt_test_15",
  :email=>"[email protected]"},
 {:id...
}]

求大神解答

require 'json'

JSON.parse(str)['users']

我把你的帖子移动到新手问题区了,这样的问题稍微查一下文档就能解决,也许你没有明白这个需求本身?(或者你是一个伸手党么?)

You need to Sign in before reply, if you don't have an account, please Sign up first.