如果我有JSON数据,如何返回JSON文件数组?

时间:2013-06-19 21:48:14

标签: ruby arrays json

我有一个格式如下的JSON文件:

[
  {
    id: 2011136021,
    tree_level: 3,
    main_category_id: 105,
    sub_nodes: [
      128001,
      128002,
      128003,
      2011136046
    ],
  }
]

我想根据父ID 2011136046返回sub_nodes的值:

sub_nodes: [
  128001,
  128002,
  128003,
  2011136046
],

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

只需一秒钟,让我们假装你有有效的JSON

require "json"

json = '{"id":2011136021,"tree_level":3,"main_category_id":105,"sub_nodes":[128001,128002,128003,2011136046]}'

obj = JSON.parse(json)
# => {"id"=>2011136021, "tree_level"=>3, "main_category_id"=>105, "sub_nodes"=>[128001, 128002, 128003, 2011136046]}

sub_nodes = obj["sub_nodes"]
# => [128001, 128002, 128003, 2011136046]

如果您想将sub_nodes转换回JSON

JSON.generate(sub_nodes)
# => "[128001,128002,128003,2011136046]"

但是现在我们可以停止假装,因为你没有有效的JSON。