Autoit 读取 Json

| 分类 技术随笔  | 标签 经验  分享  Au3 

最近用Au3写windows下的程序,想知道使用这个程序的人所在的地点,想到根据IP地址解析。目标是利用openshift上这个网站的接口,用AU3解析JSON来获取。

Google后到autoit论坛找到这个UDF结合帖子里Seeker大侠的补充实现了。

最终的代码:

;~ #noTrayIcon
opt('mustDeclareVars',1)
opt('trayIconDebug',1)
#include "WinHttp2.au3"
#include "JSON.au3"
#include "JSON_Translate.au3" ; examples of translator functions, includes JSON_pack and JSON_unpack


Func _JSONGet($json, $path, $seperator = ".")
    Local $seperatorPos,$current,$next,$l
    $seperatorPos = StringInStr($path, $seperator)

    If $seperatorPos > 0 Then
         $current = StringLeft($path, $seperatorPos - 1)
         $next = StringTrimLeft($path, $seperatorPos + StringLen($seperator) - 1)
    Else
         $current = $path
         $next = ""
    EndIf

    If _JSONIsObject($json) Then
         $l = UBound($json, 1)
	     For $i = 0 To $l - 1
	    	 If $json[$i][0] == $current Then
		    	 If $next == "" Then
		    		 return $json[$i][1]
		    	 Else
		    		 return _JSONGet($json[$i][1], $next, $seperator)
		    	 EndIf
		      EndIf
         Next
    ElseIf IsArray($json) And UBound($json, 0) == 1 And UBound($json, 1) > $current Then
        If $next == "" Then
			return $json[$current]
        Else
            return _JSONGet($json[$current], $next, $seperator)
        EndIf
	EndIf

	return $_JSONNull
EndFunc

Global $sGet = HttpGet("https://ip-json.rhcloud.com/json")
;FileWrite("ip.json", $sGet)
;Local $data = FileRead(@ScriptDir & "\ip.json")
MsgBox(0,"",$sGet)
;Local $s3='{"site": "http://ip-json.rhcloud.com", "city": "Wuxi", "region_name": "Jiangsu", "region": "04", "area_code": 0, "time_zone": "Asia/Shanghai", "longitude": 120.28859710693359, "metro_code": 0, "country_code3": "CHN", "latitude": 31.568899154663086, "postal_code": null, "dma_code": 0, "country_code": "CN", "country_name": "China", "q": "122.193.143.35"}'
Local $json=_JSONDecode($sGet)
;Local $json2=_JSONDecode($s3)

;query this object
Local $city = _JSONGet($json, "city")
Local $province = _JSONGet($json, "region_name")
Local $timezone = _JSONGet($json2, "time_zone")

msgbox(0,default,$city&$province&$timezone)

CSDN上的大侠说到多一个逗号的问题:见此


上一篇     下一篇