title: Nested JSON result in Golang from Postgres
body: <p>I'm using <a href="https://github.com/gin-gonic/gin" rel="nofollow noreferrer">gin</a> and <a href="https://github.com/go-gorp/gorp" rel="nofollow noreferrer">gorp</a></p>
  
  <p><strong>The SQL:</strong></p>
  
  <pre><code>SELECT p.project_id, p.name, 
  
  COALESCE(NULLIF(json_agg(a.*)::TEXT, '[null]'), '[]')::JSON AS apps 
  
  FROM project p LEFT JOIN app a USING (project_id) 
  
  WHERE p.user_id=19 
  
  GROUP BY p.project_id, p.name ORDER BY project_id
  </code></pre>
  
  <p><strong>The results:</strong>
  <a href="https://i.stack.imgur.com/jDUYm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jDUYm.png" alt="enter image description here"></a></p>
  
  <p><strong>Golang</strong></p>
  
  <pre><code>type Project struct {
      ID        int64           `db:"project_id, primarykey, autoincrement" json:"id"`
      UserID    int64           `db:"user_id" json:"user_id"`
      Name      string          `db:"name" json:"name"`
      Status    int             `db:"status" json:"status"`
      UpdatedAt int64           `db:"updated_at" json:"updated_at"`
      CreatedAt int64           `db:"created_at" json:"created_at"`
      Apps      json.RawMessage `json:"apps"`
  }
  
  
  func GetProjects(userID int64, page string) []Project {
      var projects []Project
  
      var err error
      _, err = db.GetDB().Select(&amp;projects, "SELECT p.project_id, p.name, COALESCE(NULLIF(json_agg(a.*)::TEXT, '[null]'), '[]')::JSON AS apps FROM project p LEFT JOIN app a USING (project_id) WHERE p.user_id=$1 GROUP BY p.project_id, p.name ORDER BY project_id LIMIT 10 OFFSET $2", userID, page)
      fmt.Println("err", err)
  
      return projects
  }
  </code></pre>
  
  <p>And returning the results using: <code>c.JSON(200, gin.H{"data": projects})</code></p>
  
  <p>It works if there's only one project</p>
  
  <p><a href="https://i.stack.imgur.com/9v47E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9v47E.png" alt="enter image description here"></a></p>
  
  <p>But if there's more than one project it gives the below error:</p>
  
  <p>The error: <code>json: error calling MarshalJSON for type json.RawMessage: invalid character '"' after top-level value</code></p>
  
  <p>Any suggestions? </p>
  
  <p>P.S: I'm a newbie in Golang</p>