dongmo6937 2016-09-07 07:49
浏览 179
已采纳

Golang从MongoDB的嵌套json数据映射中找到一个值

I am trying to receive data from my MongoDB using MGO in a map of type []map[string]interface{}

My JSON looks like this -

{
   "_id":"string",
   "brandId":123,
   "category":{
      "television":[
         {
            "cat":"T1",
            "subCategory":[
               {
                  "subCat":"T1A TV",
                  "warrantyPeriod":6
               }
            ],
            "warrantyPeriod":12
         },
         {
            "cat":"T2",
            "subCategory":[
               {
                  "subCat":"T2A",
                  "warrantyPeriod":18
               },
               {
                  "subCat":"T2B",
                  "warrantyPeriod":9
               }
            ],
            "warrantyPeriod":15
         },
         {
            "cat":"T3",
            "subCategory":[
               {
                  "subCat":"T3A",
                  "warrantyPeriod":3
               },
               {
                  "subCat":"T3B",
                  "warrantyPeriod":5
               },
               {
                  "subCat":"T3C",
                  "warrantyPeriod":7
               },
               {
                  "subCat":"T3D",
                  "warrantyPeriod":11
               }
            ],
            "warrantyPeriod":4
         }
      ],
      "television_warrantyPeriod":24
   },
   "title":"BrandName"
}

I would ideally pass in the category name i.e. 'television' and cat and subCat values which could be optional.

For e.g. something like this -

{
"categorySlug": "television",
"brandId": "123",
"model": "T2"
}

In which case I would expect to find '15' which is the warrantyPeriod value for T2 if there are no T2A or T2B specified.

My query functions look like this -

var data map[string]string
err := json.NewDecoder(r.Body).Decode(&data)
log.Println(err)
var buffer bytes.Buffer
buffer.WriteString("category.")
buffer.WriteString(data["categorySlug"])
brandId, _ := strconv.Atoi(data["brandId"])
concernedbrandandcategory := database.GetMappedFields("Brands", bson.M{"brandId": brandId, buffer.String(): bson.M{"$exists": true}}, bson.M{buffer.String(): 1})
categorymap := concernedbrandandcategory[0]
log.Println(categorymap["category"]["television"], reflect.TypeOf(categorymap))

My GetMappedFields function looks like this -

func GetMappedFields(collectionName string, query interface{}, selector interface{}) (result []map[string]interface{}) {
    MgoSession.DB(Dbname).C(collectionName).Find(query).Select(selector).All(&result)
    return
}

I'm just not able to wrap my head around this nested structure which sometimes returns a map and sometimes an interface! Any help would be highly appreciated!

  • 写回答

1条回答 默认 最新

  • duanjiao5543 2016-09-08 06:10
    关注

    you can do something like this

        majorCat := body["categorySlug"]
        category := body["category"]
        subCategory := body["subCategory"]
        brandId, err := strconv.Atoi(body["brandId"])
        if err != nil {
            log.Println(err)
        }
        result := database.GetMappedFields("Brands", bson.M{"brandId": brandId}, bson.M{"category": 1, "_id": 0})
        internalObj := result[0]["category"].(map[string]interface{})
        finalValue := internalObj["television_warrantyPeriod"]
        if category != "" {
            for _, v := range internalObj[majorCat].([]interface{}) {
                subObj := v.(map[string]interface{})
                if subObj["cat"] == category {
                    finalValue = subObj["warrantyPeriod"]
                    if subCategory != "" {
                        minorObj := subObj["subCategory"].([]interface{})
                        for _, iter := range minorObj {
                            kevVal := iter.(map[string]interface{})
                            if kevVal["subCat"] == subCategory {
                                finalValue = kevVal["warrantyPeriod"]
                            }
                        }
                    }
                }
            }
        }
    

    Hopefully this will do dynamically or you can create a struct so that it can directly be decoded into that cheers

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵