新手问题 字符串数组转换

easonlovewan · 2015年08月31日 · 最后由 easonlovewan 回复于 2015年08月31日 · 1868 次阅读

有这样一个需求:

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']

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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号