简体   繁体   English

去“ encoding / json”:元数据json字段

[英]go “encoding/json” : marshal json field

I have a PostgreSQL schema with json field's (DisplayInfo, and FormatInfo). 我有一个带有json字段(DisplayInfo和FormatInfo)的PostgreSQL模式。 Structure of this field's is dynamic. 该字段的结构是动态的。

I'can read and render it only as string (string type in render struct) : 我只能将其读取并呈现为字符串(render结构中的字符串类型):

[
 {  
  "ID":9,
  "Name":"120 №1",
  "DisplayInfo":"{\"path\": \"http://path/to/img.png\"}",
  "Format":{  
     "Code":"frame-120",
     "Width":120,
     "Height":60,
     "FormatInfo":"[{\"name\": \"\\u0413\\u043b\\u0430\\u0432\\u043d\\u043e\\u0435 \\u0438\\u0437\\u043e\\u0431\\u0440\\u0430\\u0436\\u0435\\u043d\\u0438\\u0435\", \"field_type\": \"img\", \"key\": \"path\"}]"
  },
  "Weight":0.075,
  "Application":8,
  "Url":"//path/to/game",
  "Referrer":""
 }
]

but i want output field DisplayInfo as JSON object. 但我想将输出字段DisplayInfo作为JSON对象。 How ? 怎么样 ?

My render code: 我的渲染代码:

func renderJSON(w http.ResponseWriter, obj models.Model) {
    js, err := json.Marshal(obj)

    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Write(js)
}

UPD 1 : Structure of this field's is dynamic. UPD 1:此字段的结构是动态的。 DisplayInfo may have 'path' field, or may not. DisplayInfo可能具有“路径”字段,也可能没有。 They may have additional fields. 他们可能还有其他字段。

UPD 2. I wana output DisplayInfo and FormatInfo as json-object(not string), as part of whole object , like this: UPD2。我将DisplayInfo和FormatInfo输出为json-object(不是字符串), 作为整个对象的一部分 ,如下所示:

[
 {  
  "ID":9,
  "Name":"120 №1",
  "DisplayInfo":{"path": "http://path/to/img.png"},
  "Format":{  
     "Code":"frame-120",
     "Width":120,
     "Height":60,
     "FormatInfo":[{"name": "\\u0413\\u043b\\u0430\\u0432\\u043d\\u043e\\u0435 \\u0438\\u0437\\u043e\\u0431\\u0440\\u0430\\u0436\\u0435\\u043d\\u0438\\u0435", "field_type": "img", "key": "path"}]
  },
  "Weight":0.075,
  "Application":8,
  "Url":"//path/to/game",
  "Referrer":""
 }
]

UPD 3: Structures UPD 3:结构

Actual structure is : 实际结构为:

type BannerSerializer struct {
    ID          int
    Name        string
    DisplayInfo string
    Format      formatSerializer
    Weight      float32
    Application int
    Url         string
    Referrer    string
}  

Then i trying this structure: 然后我尝试这种结构:

type BannerSerializer struct {
    ID          int
    Name        string
    DisplayInfo json.RawMessage
    Format      formatSerializer
    Weight      float32
    Application int
    Url         string
    Referrer    string
}   
  • DisplayInfo serialize as base64 string (or like base64, don't know) DisplayInfo序列化为base64字符串(或类似base64的,不知道)

Use a pointer to json.RawMessage : 使用指向json.RawMessage的指针:

type Data struct {
    Obj *json.RawMessage
}

Playground: http://play.golang.org/p/Qq9IUBDLzJ . 游乐场: http : //play.golang.org/p/Qq9IUBDLzJ

Assuming you have access to change models.Model , you can create your own type with a custom Unmarshaler that just returns the raw string: 假设您有权访问change models.Model ,则可以使用自定义Unmarshaler创建自己的类型,该Unmarshaler仅返回原始字符串:

type JSONString string

func (s JSONString) MarshalJSON() ([]byte, error) {
    return []byte(s), nil
}

Working example: 工作示例:

package main

import (
    "encoding/json"
    "fmt"
)

type JSONString string

func (s JSONString) MarshalJSON() ([]byte, error) {
    return []byte(s), nil
}

type Model struct {
    ID          int
    Name        string
    DisplayInfo JSONString
}

func main() {
    data := []byte(`{   
  "ID":9,
  "Name":"120 №1",
  "DisplayInfo":"{\"path\": \"http://path/to/img.png\"}"
}`)

    var obj Model
    err := json.Unmarshal(data, &obj)
    if err != nil {
        panic(err)
    }

    // Here comes your code
    js, err := json.Marshal(obj)

    if err != nil {
        panic(err)
    }

    fmt.Println(string(js))
}

Output: 输出:

{"ID":9,"Name":"120 №1","DisplayInfo":{"path":" http://path/to/img.png "}} {“ ID”:9,“名称”:“ 120№1”,“ DisplayInfo”:{“路径”:“ http://path/to/img.png ”}}

Playground: http://play.golang.org/p/6bcnuGjlU8 游乐场: http //play.golang.org/p/6bcnuGjlU8

You'd have to unmarshal it, here's an example: 您必须将其解组,这是一个示例:

var data []*struct {
    ID int
    DisplayInfo string
}
if err := json.Unmarshal([]byte(j), &data); err != nil {
    log.Fatal(err)
}
for _, d := range data {
    var displayInfo struct{ Path string }
    if err := json.Unmarshal([]byte(d.DisplayInfo), &displayInfo); err != nil {
        log.Fatal(err)
    }
    fmt.Println(d.ID, displayInfo.Path)
}

playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM