登录
首页 >  Golang >  Go问答

使用最佳实践解析嵌套的 JSON 结果

来源:stackoverflow

时间:2024-02-08 20:06:23 332浏览 收藏

golang学习网今天将给大家带来《使用最佳实践解析嵌套的 JSON 结果》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我有一些带有 json 嵌套结果的案例。这是示例结果,

{
  "total_result" : 25,
  "questions" : [

    {
      "id" : 1,
      "text" : "the question of user 1 here",
      "user" : {
        "id" : 5,
        "name" : "user 5",
      },
      "answers" : [
        {
          "id" : 5,
          "text" : "first answer to user 1 question",
          "user" : {
            "id" : 10,
            "name" : "user 10",
           }
        },
        {
          "id" : 6,
          "text" : "second answer to user 1 question",
          "user" : {
            "id" : 11,
            "name" : "user 11",
           }
        },
        {
          "id" : 10,
          "text" : "third answer to user 1 question",
          "user" : {
            "id" : 12,
            "name" : "user 12",
           }
        }
      ]
    },

    {
      "id" : 2,
      "text" : "the question by user 2 here",
      "user" : {
        "id" : 6,
        "name" : "user 6",
      },
      "answers" : [
        {
          "id" : 5,
          "text" : "first answer to user 2 question",
          "user" : {
            "id" : 30,
            "name" : "user 30",
           }
        },
        {
          "id" : 6,
          "text" : "second answer to user 2 question",
          "user" : {
            "id" : 20,
            "name" : "user 20",
           }
        },
        {
          "id" : 10,
          "text" : "third answer to user 2 question",
          "user" : {
            "id" : 1,
            "name" : "user 1",
           }
        }
      ]
    },

  ]
}

我的结构放在这里,

type question struct {
  id int 
  text string ...
  user user ...
  answer []answer ...
}
type user struct {
  id int ...
  name string ...
}
type answer struct {
  id int ...
  text string ...
  user user ...
}

这是获取 questionsuser.detail 的查询

query := "select text, user_id from questions limit 10 offset 10"
rows, err, := db.queryctx(ctx, query)
//handel error

var questions []question
var userids []string
for rows.next() {
  var q question
  var userid string
  //scan to `question` and `userid`
  questions = append(questions, q)
  userids = append(questions, userid)
}

这是让用户回答问题的查询

query = "select name from users where id = any($1)"
userrows, err := db.queryctx(ctx, query, pq.array(userids))
//handle error
var users []user
//scan and store to users

这是获取问题答案的查询

query = "select answers.id, answers.text, u.id, u.name from answers join questions as q on q.id=answers.question_id join users as u on u.id=answers.user_id where answers.questions_id=$1"
for i := 0; i < len(questions); i++{
  rowanswer, err := db.queryctx(ctx, query, questions[i].id)
  //handle error
  var answers []answer
  for rowanswer.next(){
    var answer answer
    //scan to answer
    append = (answers, answer)
  }
  questions[i].user.id = users[i].id
  questions[i].user.name = users[i].name
  questions[i].answer = answers
}

users

id name
1 name

问题

id text user_id
1 text 1

answers

id text question_id user_id
1 text 1 1

结果很好,代码和结果都没有问题。但是,我正在考虑 n+query 的情况,因为我确实循环以获得答案。我的问题是,这样做是否合理,或者对我的代码有什么好的建议吗?


正确答案


在获取问题中,您需要 var questionidsmapquestionidx

  • 添加选择 id
  • questionids用于获取问题id,因此可以查询的位置
  • mapquestionidx 用于在切片中保存问题 id 和索引。 注意question_id是键,index是值

所以看起来像这样

query := "select id, text, user_id from questions limit 10 offset 10"
rows, err, := db.queryctx(ctx, query)
//handel error

var questions []question
var userids []string

questionids := make([]int, 0, 10) // because limit is 10
mapquestionidx := make(map[int]int)
idx := 0

for rows.next() {
  var q question
  var userid string
  //scan to `question` and `userid`
  questions = append(questions, q)
  userids = append(questions, userid)

  questionids = append(questionids, q.id)
  mapquestionidx[q.id] = idx
  idx++
}

通过查询来获取问题的答案

  • 添加选择question_id
// add select question_id
query = "select q.id question_id, answers.id, answers.text, u.id, u.name from answers join questions as q on q.id=answers.question_id join users as u on u.id=answers.user_id where answers.questions_id in ($1)"

  rowanswer, err := db.queryctx(ctx, query, questionids) // questionids from above
  //handle error
  for rowanswer.next(){
    var answer answer
    var question_id int
    //scan to answer and question_id

    i := mapquestionidx[question_id]
    
    questions[i].user.id = users[i].id
    questions[i].user.name = users[i].name

    if questions[i].answer == nil {
      questions[i].answer = make([]answer, 0)
    }
    questions[i].answer = append(questions[i].answer, answer)
  }

您可以结合使用结构标记和 encoding/json 来正确解组结果。

您的用例示例:

将您的类型重新声明为

type question struct {
  id int `json:"id"`
  text string `json:"text"`
  user user `json:"user"`
  answer []answer `json:"answer"`

// fill the rest yourself
...
}

简单地解组:

someDummyQuestionsResult := []byte{
    {
     // some example
    }
 }

 var questions []Question
 err := json.Unmarshal(someDummyQuestionsResult , &questions)

 fmt.Println(questions)

今天关于《使用最佳实践解析嵌套的 JSON 结果》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>