J
J
jxs2018-09-10 13:56:44
Ruby on Rails
jxs, 2018-09-10 13:56:44

How to display data in Json in hierarchical form?

My JSON looks like this:

[
  {
    "id": "197",
    "user_id": 471,
    "position": "CEO",
    "child_id_users": null
  },
  {
    "id": "338",
    "user_id": 342,
    "position": "Deputy. director",
    "child_id_users": "471"
  },
  {
    "id": "411",
    "user_id": 347,
    "position": "Chief Accountant",
    "child_id_users": "342"
  },
  {
    "id": "543",
    "user_id": 1003,
    "position": "personal driver №1",
    "child_id_users": "471"
  },
  {
    "id": "521",
    "user_id": 867,
    "position": "personal driver №2",
    "child_id_users": "342"
  },
...
]

I want the JSON to be displayed in a hierarchical style so that an "org chart" can be created on the client. That is, it should look something like this:
[
  {
    "id": "197",
    "user_id": 471,
    "position": "CEO",
    "child_id_users": null,
     "children": [{
           {
             "id": "338",
             "user_id": 342,
             "position": "Deputy. director",
             "child_id_users": "471",
             "children": [{       
                           "id": "411",
                           "user_id": 347,
                           "position": "Chief Accountant",
                           "child_id_users": "342"
                          },
                          {
                           "id": "521",
                           "user_id": 867,
                           "position": "personal driver №2",
                           "child_id_users": "342"
                          }]
            },
            {
              "id": "543",
              "user_id": 1003,
              "position": "personal driver №1",
              "child_id_users": "471"
             }

      }]
  }
]

Is it possible to implement something similar? Here is my "index" from the controller at the moment:
def index
  @org_charts = OrgChart.all
  render json: JSON.pretty_generate(@org_charts.as_json)
end

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Goryachkin, 2015-03-17
@Rattlesneyk

So, what exactly do you need to get from there? In general, logically, you need data from data, then you need to do this:

$res = json_decode($result, true);
if ($res['success']) {
     for($i = 0; $i < $res['totalNumRows']; $i++) {
         $elem = $res['data'][$i]; //$elem и есть ваши данные далее делайте с ними что хотите
         echo $elem['clicks'];//Выводим клики
     }
} else {
    //Тут обработка если получил false
}

F
FanatPHP, 2015-03-17
@FanatPHP

Perhaps this is because you do not have json, but an array?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question