dourao1896 2017-08-07 12:40
浏览 52
已采纳

序列化为JSON动态结构

All examples of working with JSON describe how to serialize to JSON simple or user types (like a struct).

But I have a different case: a) I don't know the fields of my type/object b) every object will have different types.

Here is my case in pseudocode:

while `select * from item` do
  while `select fieldname, fieldvalue from fields where fields.itemid = item.id` do
    ...

For each entity in my database I get field names and field values. In the result I need to get something like this:

{
  "item.field1": value,
  ...
  "item.fieldN": value,
  "custom_fields": {
     "fields.field1": value,
      ...
     "fields.fieldK": value
  }
}

What is the best way to do it in Go? Is there any useful libraries or functions in standard library ?

Update: The source of data is the database. In the result i need to get JSON as string to POST it to external web service. So, the program just read data from database and make POST requests to REST service.

  • 写回答

1条回答 默认 最新

  • dongshanfan1941 2017-08-07 13:04
    关注

    What exactly is your target type supposed to be? It can't be a struct since you do not know the fields beforehand.

    The only fitting type to me seems to be a map of type map[string]interface{}: with it any nested structure can be achieved:

    a := map[string]interface{}{
        "item.field1": "val1",
        "item.field2": "val2",
        "item.fieldN": "valN",
        "custom_fields": map[string]interface{}{
            "fields.field1": "cval1",
            "fields.field2": "cval2",
        },
    }
    b, err := json.Marshal(a)
    

    See playground sample here.

    Filling this structure from a database as you hinted at should probably be a custom script (not using json).

    Note: custom_fields can also be of other types depending on what type the value column is in the database. If the value column is a string use map[string]string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?