How to retrieve database with tree structure to json

How does to solve this case. I have database tree, and a category table.

I want to retrieve data that make structure of tree. with json file

    "status": 1,
    "message": "Success",
    "Data": [
            "id": 1,
            "title": "Electronic",
            "child": {
                "id": 2,
                "title": "Computer"
                "child": {//*computer's child*//}

Have you tried anything? Does it work?

I’m newbie in golang, I just can retrieve data from db with single row.
In SQL query I used join.
Would you have any sollusion?

If you want to encode data as JSON, the encoding/json package can be used. There is an article on the official blog that gives an introduction.

I know that’s, but the point is how if I have a tree structure in DB and want to retrieve it to json.

this the query that i used in sql

SELECT t1.title AS lev1, t2.title as lev2, t3.title as lev3, t4.title as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent_id = t1.id_category
LEFT JOIN category AS t3 ON t3.parent_id = t2.id_category
LEFT JOIN category AS t4 ON t4.parent_id = t3.id_category
WHERE t1.title = 'ELECTRONIC';

the result

and I want to retrieve it to json like I mention in my post

Then read the data into equivalent structs or map[string]interface{} and use the already mentioned encoding/json package to get the JSON representation.

If there are any problems, show what you have so far and explain where you got stuck.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.