Go to parse Prometheus data

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Access an API that returns the following data:

{" status ":" Success "," data ": {" Resulttype ":" Matrix "," result ": [{" metric ": {}," values ": [[ 1473820558.361, "28765"],[1473820573.361, "28768"],[1473820588.361, "28772"],[1473820603.361, "28776"],[ 1473820618.361, "28780"],[1473820633.361, "28783"],[1473820648.361, "28786"],[1473820663.361, "28790"],[ 1473820678.361, "28793"],[1473820693.361, "28796"],[1473820708.361, "28799"],[1473820723.361, "28802"],[ 1473820738.361, "28806"],[1473820753.361, "28809"],[1473820768.361, "28817"],[1473820783.361, "28829"],[ 1473820798.361, "28832"],[1473820813.361, "28858"],[1473820828.361, "28862"],[1473820843.361, "28867"],[ 1473820858.361, "28873"]}]}}


JS,err: =Simplejson. Newjson (body)
  iferr!=nil{
  Panic(err. Error ())
    }
  //parse array
 arr,_: =js. Get ("Data"). Get ("result"). GetIndex (0). Get ("values"). Array ()
 length: =len(arr)
  fori: =0;  i<length;  i++{
 x:=*js. Get ("Data"). Get ("result"). GetIndex (0). Get ("values"). GetIndex (i). GetIndex (0))
  //fmt. Println (*js. Get ("Data"). Get ("result"). GetIndex (0). Get ("values"). GetIndex (i). GetIndex (1))
    }

Access an API that returns the following data:

{  "Data":{    "Trend":{      " Fields":[ "Min_time", "last_px", "avg_px", "Business_amount" ],      "600570.SS":[[ 201501090930, 54.98, 54.98, 28327 ], [ 201501090931, 54.63, 54.829486, 49700         ]      ]    }}}

Need to parse the JSON data after 600570.SS, using the Simplejson package

js, err: = Simplejson. Newjson ([]byte (str))  check  (Err) arr, _: = js. get  ( "data" ). get  (" trend "). get  (" 600570.SS "). array  ()

But the ARR data returned, with 18-like martial arts are not resolved. The arr type theory is a interface{} type, but it contains four sets of data, and there is no way to parse this kind of JSON data on an online document. After repeated attempts, tested with Reflect.type, the system finds that ARR is identified as []interface type, so the type asserts after traversal. This time can be divided into the data inside, the system and the data inside the judgment as JSON. Number data type. And then there's no more .... After this groping, for the null interface, type assertion, the JSON package inside some of the settings have a deeper understanding: The Null interface is because it is flexible, so in the use of a series of judgments.

On the code:

 PackageMainImport("Encoding/json"    "FMT"    "Github.com/bitly/go-simplejson"    "Io/ioutil"    "Net/http"    //"reflect"    "RegExp"    "StrConv"    "Strings")//const Blksize int = 10000typeTrendstruct{DateInt64Last_pxfloat32 //Latest PriceAvg_pxfloat32 //Average priceVolumnfloat32 //Volume}var(Lines []stringBlkslen []intIsgbBOOL)funcCheck (err error) {ifErr! =Nil{Panic(Err. Error ())}}funcGet (URLstring) ([]byte, error) {defer func() {ifERR: =Recover(); Err! =Nil{FMT. PRINTLN (Err)}} () resp, err: = http. Get (URL) check (err)//println (resp. StatusCode)    ifResp. StatusCode! = ${Panic("Fuck")    }returnIoutil. ReadAll (resp. Body)}funcStrip (srcstring)string{src = strings. ToLower (SRC) Re, _: = Regexp.compile (' <!doctype.*?> ') src = Re. Replaceallstring (SRC,"") Re, _ = Regexp.compile (' <!--. *?--> ') src = Re. Replaceallstring (SRC,"") Re, _ = Regexp.compile (' <script[\S\s]+?</script> ') src = Re. Replaceallstring (SRC,"") Re, _ = Regexp.compile (' <style[\S\s]+?</style> ') src = Re. Replaceallstring (SRC,"") Re, _ = Regexp.compile (' <.*?> ') src = Re. Replaceallstring (SRC,"") Re, _ = Regexp.compile (' & {1,5};|&#. {1,5}; ') src = Re. Replaceallstring (SRC,"") src = strings. Replace (SRC,"\ r \ n","\ n",-1) src = strings. Replace (SRC,"\ r","\ n",-1)returnSrcfuncDo (URLstring)string{body, err: = Get (URL) check (err) PlainText: = Strip (string(body))returnPlainText}funcMain () {str: = Do ("HTTP://XXX:8081/QUOTE/V1/TREND?PROD_CODE=600570.SS&FIELDS=LAST_PX,BUSINESS_AMOUNT,AVG_PX") js, err: = Simplejson. Newjson ([]byte(str)) Check (Err) arr, _: = js. Get ("Data"). Get ("Trend"). Get ("600570.SS"). Array () T: =Len(arr) StockData: = trend{} Trends: = Make([]trend,0, T) for_, V: =Rangearr {//Right here I make type judgmentsValue, _: = V. ([]Interface{}) forK, U: =RangeValue {x, _: = U. (JSON. Number)//Type assertionY, _: = StrConv. Parsefloat (string(x), -)//Convert character model to float64            //v: = reflect. ValueOf (k)            //fmt. Println ("type:", V.type ())            SwitchK Case0: Stockdata.date =Int64(y) Case1: stockdata.last_px =float32(y) Case2: Stockdata.volumn =float32(y) Case3: stockdata.avg_px =float32(y)default: FMT. Println ("This element does not exist in the struct")}} trends =Append(Trends, StockData)} Fmt. Println (Trends)}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.