dongzhan8620
2016-03-31 05:32
浏览 276

golang,如何在simplejson中解码json数组的项目?

incoming String is:

     {"status_list":[
         {"m_id":70,"m_status":"OK","m_status_code":200,"reported":false},
         {"m_id":71,"m_status":"Send Message Over Time","m_status_code":800,"reported":false},
         {"m_id":72,"m_status":"OK","m_status_code":200,"reported":false},
         {"m_id":73,"m_status":"OK","m_status_code":200,"reported":false}
         ]
      }

How can I get the m_status field of the last status element?

The way I am using is

import github.com/bitly/go-simplejson"

....
jsonRequest, _ := simplejson.NewJson([]byte(incommingString))
mArray := jsonRequest.Get("status_list").MustArray()
mItem := mArray[3]
fmt.printf("mItem: %")
m3StatusCode := mItem["m_status_code"]   //<---<< Can't compile

I got:

invalid operation: mItem["m_status_code"] (type interface {} does not support indexing)

If I remove last line code. I can print out mItem as

mItem: : map[m_id:73 m_status:OK m_status_code:200 reported:%!s(bool=false)]

QUESTION: How can I fetch m_status_code value?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dshmkgq558192365 2016-03-31 05:41
    已采纳

    You will have to do a type assertion first.

    m, ok := mItem.(map[string]interface{})
    if(!ok){
        fmt.Println("Invalide data")
    }
    
    fmt.Println(m["m_status_code"])
    

    This is because mItem is not actually a map. Its an interface{}. simplejson's MustArray returns a []interface{}.

    So you have to assert that the value stored in mItem is of a type you can use an index m_status_code on.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题