Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

640
Visualizações
How I can write the value of mongo objectid in json string in golang

The objectid is always unique and unpredictable. I want that, this var should take value of primitive.NewObjectID.Hex()

var mockData = `{"status":201,"message":"User Created Successfully!","data":{"data":"{"InsertedID":primitive.NewObjectID().Hex()}"}}`

But writing it like this gives me a straight string in output.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You have to "break" the string literal and concatenate the parts using +:

var mockData = `{"status":201,"message":"User Created Successfully!","data":{"data":{"InsertedID":"` + primitive.NewObjectID().Hex() + `"}}}`

This will work because the hex object ID does not need any special escaping in JSON, but in general you should use the encoding/json package to generate valid JSON (which knows about proper escaping).

Using the encoding/json package this is how it could look like:

var s struct {
    Status  int    `json:"status"`
    Message string `json:"message"`
    Data    struct {
        Data struct {
            InsertedID string
        } `json:"data"`
    } `json:"data"`
}
s.Status = 201
s.Message = "User Created Successfully!"
s.Data.Data.InsertedID = primitive.NewObjectID().Hex()

out, err := json.Marshal(s)
if err != nil {
    panic(err)
}
fmt.Println(string(out))

Try the examples on the Go Playground.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda