Jump to content

xml with chrome, json with IE

Recommended Posts

Hi Guys, 

Since I'm able to get a Dell equipment warranty status thanks to my API key, I'm using an UDF to extract data from an XML file and get the end date. > 

Thing is, when using InetGet, the original file is in JSON format and the UDF is not working anymore, even if I download the file with the xml extension. Therefore, and when I manually download the page with Chrome, I have a proper XML file where the UDF is working fine.

Here's my code:

Local $sFilePath = @DesktopDir & "\3MTXM12.xml"
InetGet("https://sandbox.api.dell.com/support/assetinfo/v4/getassetwarranty/APIKEYICANNOTGIVE", @DesktopDir & "\3MTXM12.xml", $INET_FORCERELOAD)

Local $xmlPath = @DesktopDir & "\3MTXM12.xml"
If Not FileExists($xmlPath) Then Exit
$file = FileRead($xmlPath)
$file = StringReplace($file, @LF, '')
$file = StringSplit($file, @CR, 1)

MsgBox(0, 'DONE!!!', StringTrimRight(XMLget($file, 'AssetEntitlement\EndDate'),9))

Func XMLget($file, $Path)
    $Path = StringSplit($Path, '/\|', 0)
    $lastline = 0
    For $lvl = 1 To $Path[0] Step 1
        For $line = $lastline To $file[0] Step 1
            $lastline = $line
            $hstart = StringInStr($file[$line], '<' & $Path[$lvl] & '>', 0)
            $hstarta = StringInStr($file[$line], '<' & $Path[$lvl] & ' ', 0)
            If $hstart Or $hstarta Then
                If $lvl == $Path[0] Then
                    If $hstart Then
                        $end = StringInStr($file[$line], '</' & $Path[$lvl] & '>', 0)
                        If $end Then
                            $hstart = $hstart + StringLen('<' & $Path[$lvl] & '>')
                            Return StringMid($file[$line], $hstart, $end - $hstart)
                    If $hstarta Then
                        $end = StringInStr($file[$line], '/>', 0)
                        If $end Then
                            $hstarta = $hstarta + StringLen('<' & $Path[$lvl] & ' ')
                            $return = StringMid($file[$line], $hstarta, $end - $hstarta)
                            Return $return
                        $ends = StringInStr($file[$line], '>', 0)
                        If $ends Then
                            $hstart = $ends + 1
                            $end = StringInStr($file[$line], '</' & $Path[$lvl] & '>', 0)
                            If $end Then
                                $return = StringMid($file[$line], $hstart, $end - $hstart)
                                Return $return
                ContinueLoop 2
        If $line == $file[0] Then ExitLoop
    Return 'not found'
EndFunc ;==>XMLget


I even tried to convert the json to xml > https://www.autoitscript.com/forum/topic/185717-js-json-to-xml/

I took a look here https://www.autoitscript.com/forum/topic/104150-json-udf-library-fully-rfc4627-compliant/ but I don't understand anything :/


The XML read UDF is just perfect for my needs but I'm stuck here... 

Thanks for any help you can provide :)




~~~ Doom Shall Never Die, Only The Players ~~~

Link to post
Share on other sites

Hi @31290

here is two suggestions for you. Hope they are useful.

Let me know if you have any questions, i will do my best to answer :)

$oXML = ObjCreate("Microsoft.XMLDOM")
$oXML.Load("3MTXM12.xml"); or $oXML.LoadXML(FileRead("3MTXM12.xml"))
$oNodes = $oXML.SelectNodes("./AssetWarrantyDTO/AssetWarrantyResponse/AssetWarrantyResponse/AssetEntitlementData/AssetEntitlement/EndDate"); or $oNodes = $oXML.SelectNodes("//AssetEntitlement/EndDate")
For $oNode In $oNodes


$oSC = ObjCreate("ScriptControl")
$oSC.language = "JScript"
$oSC.Eval("Array.prototype.Item = function(i){return this[i];};")
$oJSON = $oSC.Eval("("&FileRead("3MTXM12.json")&")")
For $i=0 To $oJSON.AssetWarrantyResponse.length-1
    For $j=0 To $oJSON.AssetWarrantyResponse.Item($i).AssetEntitlementData.length-1


Edited by genius257
Link to post
Share on other sites

Hi Genius257, 

Thanks a lot for your input. 

But in the meantime, I found this solution:

; Creating the object
$oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
$oHTTP.Open("GET", "https://sandbox.apidp.dell.com/support/assetinfo/V4/getassetwarranty/ASSET?apikey=XXXX", False)
$oHTTP.SetRequestHeader("Accept", "application/xml")

; Download the body response if any, and get the server status response code.
$oReceived = $oHTTP.ResponseText
$oStatusCode = $oHTTP.Status

If $oStatusCode <> 200 then
 MsgBox(4096, "Response code", $oStatusCode)

; Saves the body response regardless of the Response code
 $file = FileOpen(@TempDir & "\update222.xml", 2) ; The value of 2 overwrites the file if it already exists
 FileWrite($file, $oReceived)

Can be useful if someone ever need it :)



~~~ Doom Shall Never Die, Only The Players ~~~

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By rudi
      is there a way to use inetget() to catch the content of an 404 error page returned by the web server?
      $URL="https://www.autoitscript.com/ThisPathDoesntExist" $content=InetGet($url,"c:\temp\xxx.html",1+2) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $content = "' & $content & """" & @CRLF & "@Extended: """ & @extended & """" & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console  
      >"C:\Program Files (x86)\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Program Files (x86)\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "C:\temp\löschmich\xxx.au3" /UserParams +>15:27:05 Starting AutoIt3Wrapper v.18.708.1148.0 SciTE v. Keyboard:00000407 OS:WIN_10/ CPU:X64 OS:X64 Environment(Language:0407) CodePage:0 utf8.auto.check:4 +> SciTEDir => C:\Program Files (x86)\AutoIt3\SciTE UserDir => C:\Users\admin.AD\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper SCITE_USERHOME => C:\Users\admin.AD\AppData\Local\AutoIt v3\SciTE >Running AU3Check ( from:C:\Program Files (x86)\AutoIt3 input:C:\temp\löschmich\xxx.au3 +>15:27:05 AU3Check ended.rc:0 >Running:(\Program Files (x86)\AutoIt3\autoit3.exe "C:\temp\löschmich\xxx.au3" --> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop @@ Debug(6) : $content = "0" @Extended: "0" >Error code: 13 +>15:27:05 AutoIt3.exe ended.rc:0 +>15:27:05 AutoIt3Wrapper Finished. >Exit code: 0 Time: 0.9361  
      The browser (I use Chrome) is displaying this 404 page: (That's what I'd like to catch)
      Not Found The requested URL /ThisPathDoesntExist was not found on this server. html code (Browser ctrl+u):
      <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>404 Not Found</title> </head><body> <h1>Not Found</h1> <p>The requested URL /ThisPathDoesntExist was not found on this server.</p> </body></html>  
      Wireshark response 404 packet:
      Hypertext Transfer Protocol HTTP/1.1 404 Not Found\r\n Server: nginx\r\n Date: Wed, 06 Apr 2022 13:34:26 GMT\r\n Content-Type: text/html; charset=iso-8859-1\r\n Content-Length: 217\r\n Connection: keep-alive\r\n Vary: Accept-Encoding\r\n \r\n [HTTP response 1/1] [Time since request: 0.056074000 seconds] [Request in frame: 1476] [Request URI: http://www.autoitscript.com/ThisPathDoesntExist] File Data: 217 bytes Line-based text data: text/html (7 lines) <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>404 Not Found</title> </head><body> <h1>Not Found</h1> <p>The requested URL /ThisPathDoesntExist was not found on this server.</p> </body></html> any suggestions appreciated,
      <edit> also tried _inetgetsource() and inetread() </edit>
    • By rot3r
      Hi friends,
      I'm using json.au3 to register some data in my server, everything work fine except the data that i send in utf8 format like names saved as ????? .
      i think something mess with inetget cause this problem
      can you help me please?
      $sAdditionalData = "secret_key=" & $secret_key_verify & "&slm_action=slm_check&license_key=" & $license_key&"&first_name="&$first_name $data = _INetGetSource($sDomain&'/?'&$sAdditionalData) $object = json_decode($data) Json_Dump($data) $response = json_get($object, '.first_name')  
    • By Ward
      JSON (Javascript Object Notation) is a popular data-interchange format and supported by a lot of script languages. On AutoIt, there is already a >JSON UDF written by Gabriel Boehme. It is good but too slow, and not supports unicode and control characters very well. So I write a new one (and of course, fast one as usual).

      I use a machine code version of JSON parser called "jsmn". jsmn not only supports standard JSON, but also accepts some non-strict JSON string. See below for example.
      Important Update!!
      I rename the library from jsmn.au3 to json.au3. All function names are changed, too.
      Decoding Function
      Json_Decode($Json) $Json can be a standard or non-standard JSON string. For example, it accepts:
      { server: example.com port: 80 message: "this looks like a config file" } The most JSON data type will be decoded into corresponding AutoIt variable, including 1D array, string, number, true, false, and null. JSON object will be decoded into "Windows Scripting Dictionary Object" retuned from ObjCreate("Scripting.Dictionary"). AutoIt build-in functions like IsArray, IsBool, etc. can be used to check the returned data type. But for Object and Null, Json_IsObject() and Json_IsNull() should be used.

      If the input JSON string is invalid, @Error will be set to $JSMN_ERROR_INVAL. And if the input JSON string is not finish (maybe read from stream?), @Error will be set to $JSMN_ERROR_PART.

      Encoding Function
      Json_Encode($Data, $Option = 0, $Indent = "\t", $ArraySep = ",\r\n", $ObjectSep = ",\r\n", $ColonSep = ": ") $Data can be a string, number, bool, keyword(default or null), 1D arrry, or "Scripting.Dictionary" COM object. Ptr will be converted to number, Binary will be converted to string in UTF8 encoding. Other unsupported types like 2D array, dllstruct or object will be encoded into null.

      $Option is bitmask consisting following constant:
      $JSON_UNESCAPED_ASCII ; Don't escape ascii charcters between chr(1) ~ chr(0x1f) $JSON_UNESCAPED_UNICODE ; Encode multibyte Unicode characters literally $JSON_UNESCAPED_SLASHES ; Don't escape / $JSON_HEX_TAG ; All < and > are converted to \u003C and \u003E $JSON_HEX_AMP ; All &amp;amp;amp;amp;s are converted to \u0026 $JSON_HEX_APOS ; All ' are converted to \u0027 $JSON_HEX_QUOT ; All " are converted to \u0022 $JSON_PRETTY_PRINT ; Use whitespace in returned data to format it $JSON_STRICT_PRINT ; Make sure returned JSON string is RFC4627 compliant $JSON_UNQUOTED_STRING ; Output unquoted string if possible (conflicting with $JSMN_STRICT_PRINT) Most encoding option have the same means like PHP's json_enocde() function. When $JSON_PRETTY_PRINT is set, output format can be change by other 4 parameters ($Indent, $ArraySep, $ObjectSep, and $ColonSep). Because these 4 output format parameters will be checked inside Jsmn_Encode() function, returned string will be always accepted by Jsmn_Decode(). $JSON_UNQUOTED_STRING can be used to output unquoted string that also accetped by Jsmn_Decode().

      $JSON_STRICT_PRINT is used to check output format setting and avoid non-standard JSON output. So this option is conflicting with $JSON_UNQUOTED_STRING.

      Get and Put Functions
      Json_Put(ByRef $Var, $Notation, $Data, $CheckExists = False) Json_Get(ByRef $Var, $Notation) These functions helps user to access object or array more easily. Both dot notation and square bracket notation can be supported. Json_Put() by default will create non-exists objects and arrays. For example:
      Local $Obj Json_Put($Obj, ".foo", "foo") Json_Put($Obj, ".bar[0]", "bar") Json_Put($Obj, ".test[1].foo.bar[2].foo.bar", "Test") Local $Test = Json_Get($Obj, '["test"][1]["foo"]["bar"][2]["foo"]["bar"]') ; "Test" Object Help Functions
      Json_ObjCreate() Json_ObjPut(ByRef $Object, $Key, $Value) Json_ObjGet(ByRef $Object, $Key) Json_ObjDelete(ByRef $Object, $Key) Json_ObjExists(ByRef $Object, $Key) Json_ObjGetCount(ByRef $Object) Json_ObjGetKeys(ByRef $Object) Json_ObjClear(ByRef $Object) These functions are just warps of "Scripting.Dictionary" COM object. You can use these functions if you are not already familiar with it.
      == Update 2013/05/19 ==
      * Add Jsmn_Encode() option "$JSMN_UNESCAPED_ASCII". Now the default output of Json_Encode() is exactly the same as PHP's json_encode() function (for example, chr(1) will be encoded into u0001).
      $JSON_UNESCAPED_ASCII ; Don't escape ascii charcters between chr(1) ~ chr(0x1f)  
      == Update 2015/01/08 ==
      * Rename the library from jsmn.au3 to json.au3. All function names are changed, too.
      * Add Json_Put() and Json_Get()
      * Add Null support
      * Using BinaryCall.au3 to loading the machine code.
      == Update 2018/01/13==   (Jos)
      * Add JsonDump() to list all Json Keys and their values to easily figure out what they are.
      == Update 2018/10/01==  (Jos)
      * Fixed JsonDump() some fields and values were not showing as discussed here  - tnx @TheXman .
      == Update 2018/10/01b==   (Jos)
      * Added Json_ObjGetItems, Tidied source and fixed au3check warnings - tnx @TheXman .
      == Update 2018/10/28==   (Jos)
      * Added declaration for $value to avoid au3check warning - tnx @DerPensionist
      == Update 2018/12/16==   (Jos)
      * Added another declaration for $value to avoid au3check warning  and updated the version at the top - tnx @maniootek
      == Update 2018/12/29==   (Jos)
      * Changed Json_ObjGet() and Json_ObjExists() to allow for multilevel object in string.
      == Update 2019/01/17==   (Jos)
      * Added support for DOT notation in JSON functions.
      == Update 2019/07/15==   (Jos)
      *  Added support for reading keys with a dot inside when using a dot as separator (updated)
      == Update 2021/11/18==   (TheXman)
      * Update details in below post:  
      == Update 2021/11/20==   (TheXman)
      * Minor RegEx update, no change to the functionality or result._Json(2021.11.20).zip
    • By mLipok
      I was asking @eltorro serveral times for any support  for XML DOM wrapper (COM) - with no success  
          So I took matters into my hands ..... I want to present XMLWrapperEx.au3 - BETA Version
      Want to join to the project ?
      Here is some description:
      ; #INDEX# ======================================================================================================================= ; Title .........: XMLWrapperEx.au3 ; AutoIt Version : ; Language ......: English ; Description ...: Functions to use for reading and writing XML using msxml. ; Remarks .......: BETA Version ; Author ........: mLipok ; Version .......: "" ; _XML_MiscProperty_UDFVersion() #CS This UDF is created on the basis of: https://www.autoitscript.com/forum/topic/19848-xml-dom-wrapper-com/ For this reason, I attach also the last known (to me) previous version ($_XMLUDFVER = "" _XMLDomWrapper_1.0.3.98_CN.au3 ) For the same reason I continue to recognize the achievements of the work of my predecessors (they are still noted in each Function header). . . . . !!!!!!!!! This is BETA VERSION (all could be changed) !!!!!!!!! . . . WORK IN PROGRES INFORMATION: For now 2015-09-01 the descripion (Function Header) can not entirely correctly describe the function. TODO: in many places I used "TODO" as a keyword to find what should be done in future . I want to: PREVENT THIS: The unfortunate nature of both the scripts is that the func return results are strings or arrays instead of objects. .     I want to: USE THIS CONCEPT:     .   All function should use Refernce to the object as first Function parameter     .   All function should return in most cases objects. There should be separate functions to Change Object collection to array     .   All function should use COM Error Handler in local scope.     .   All function should return @error which are defined in #Region XMLWrapperEx.au3 - @ERROR Enums     .    All function should have the same naming convention     .    All variables should have the same naming convention     .    There should not to be any Global Variable - exception is $g__oXMLDOM_Events     .   It should be possible easy to use XML DOM Events     .        https://msdn.microsoft.com/en-us/library/ms764697(v=vs.85).aspx     .   It should be possible easy to Debug     .    Ultimately, you should be able to do anything with your XML without having to use your own Error Handler. #CE  
      More info inside zip archive.
      This UDF can be downloaded from here:
      This UDF was formerly named:   XMLWrapperEx.au3 
    • By TheXman
      This UDF brings the power and flexibility of jq to AutoIt scripts.  jq is an open-source, powerful, and flexible command-line based JSON processor.  As it says on their website, jq is like 'sed' for JSON.  jq can be used for the simplest of tasks like retrieving JSON objects and values (parsing), to very advanced JSON processing using its numerous built-in functions and conditional processing.  Its built-in functions can handle math, selection, conditional processing, mapping, object and array manipulation, flattening, reduction, grouping, and much more.  You can even create your own jq functions.  You can learn more about jq and even play with it in real-time, using jq's online jq playground, all on their website.
      Here and some helpful links to get you more familiar with jq, what can be done with it, its built-in functions, and its syntax.
      jq Website: https://stedolan.github.io/jq/ jq Manual: https://stedolan.github.io/jq/manual/ jqWiki (FAQ, Cookbook, Advanced Topics) https://github.com/stedolan/jq/wiki jq Online Testing Playground: https://jqplay.org/ jq is a single 32 or 64 bit executable that has no other dependencies.  Just like using the SQLite UDF, the only requirement to use this UDF is that the jq executable reside in a location in which the UDF can execute it.  The latest win32 & win64 versions have been included in the UDF download.  You can always get newer versions from the jq website.
      I don't consider this UDF as a replacement for some of the other JSON UDFs like the one based on JSMN.  If speed and simple JSON parsing are your primary goals, then other UDFs may be a better choice.  However, if you like having the power to do just about anything related to JSON processing/manipulation, using a single UDF, then jq may be worth checking out.  It can be used by novices and experts alike.  Below, is a brief explanation of how jq works, how to use the jq UDF, and a few examples of how to do some simple tasks.  If you want to learn more about jq and what it can do, I would highly suggest checking out the jq website and some of the other resources listed above.
      jq at a high level
      Like 'sed', jq reads JSON in, either through STDIN or one or more files, processes it thru one or more "filters", and outputs the results.  You can, optionally, supply "options" that affect how it reads the input, where it gets its "filters", and how it writes its output.  It looks a little like this:
      JSON ---> jq processor (using supplied filters and options) ---> Output
      So in jq lingo, you basically use "Filters" to tell jq what you want it to do.  So in the UDF file, that is why the main functions ( _jqExec() and _jqExecFile() ) refer to filters and options.  Please make note that jq works with relatively strict JSON.  This means that all JSON read must be conform to the standard.  Luckily, jq is pretty good at identifying where a format error exists in non standard JSON.
      The jq UDF
      There are 2 main funtions in the UDF file, _jqExec and jqExecFile.  With these 2 functions, you can pretty much do anything that jq can do.  The only difference between to two functions is whether the JSON is supplied by a string or a file.  The 2 primary functions simply call the jq executable with the supplied information, after properly formatting the parameters.  There are additional functions in the UDF to easily pretty-print your json, compact-print your json, dump the json data with its associated paths, and see if specific JSON keys exist, but they all just execute the _jqExec or _jqExecFile function with the proper filter.  There are also a couple of extra functions to display what version of the UDF and jq executable you are currently using.  There are also a couple of functions to enable and disable logging of jq information for debugging purposes.  Most of the jq UDF file functions return an @error if unsuccessful.  Some also include @extended info.  Please see the actual function headers for more information on their usage and return values.
      The 2 primary functions below just format your jq request and pass it on the jq executable.  The functions will also properly escape double quotes (") that are used in the filter.  For most simple tasks, you just need to supply the JSON source and a filter.
      _jqExec($sJson, $sFilter, $sOptions = Default, $sWorkingDir = Default) Or _jqExecFile($sJsonFile, $sFilter, $sOptions = Default, $sWorkingDir = Default) Using jq in your script
      As stated earlier, the jq executable must reside somewhere where the script can locate and execute it.  The _jqInit() function always has to be executed before any jq processing occurs.  _jqInit() merely locates the executable or uses the supplied path.  It also clears any previous debug log.  The jq UDF folder contains a jq example script that has several examples to how to do some of the most common JSON processing tasks.  Here are a few examples to get you started:

      How to pretty-print some JSON
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"fruits":[{"Apple":{"color":"Red","season":"Fall"}}, {"Banana":{"color":"Yellow","season":"Summer"}}]}' $sCmdOutput = _jqPrettyPrintJson($sJson) ConsoleWrite(@CRLF & "Pretty-Print JSON" & @CRLF & $sCmdOutput & @CRLF) How to compact-print some JSON
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{ "fruits" : [{"Apple" : {"color":"Red","season":"Fall"}}, {"Banana":{"color":"Yellow","season":"Summer"}}]}' $sCmdOutput = _jqCompactPrintJson($sJson) ConsoleWrite(@CRLF & "Compact-Print JSON" & @CRLF & $sCmdOutput & @CRLF) Dump JSON data (paths and values)
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{ "fruits" : [{"Apple" : {"color":"Red","season":"Fall"}}, {"Banana":{"color":"Yellow","season":"Summer"}}]}' $sCmdOutput = _jqDump($sJson) ConsoleWrite(@CRLF & "Dump JSON paths and values" & @CRLF & $sCmdOutput & @CRLF) How to GET JSON values
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple" : {"color":"Red","season":"Fall"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = '.Banana.color' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("Get color of banana" & @CRLF) ConsoleWrite("Input: : " & _jqCompactPrintJson($sJson) & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF) or
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple" : {"color":"Red","season":"Fall"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = 'getpath(["Banana", "color"])' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("Get color of banana" & @CRLF) ConsoleWrite("Input: : " & _jqCompactPrintJson($sJson) & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF)  
      Check for the existence of a key
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple":{"color":"Red","season":"Fall"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = '.Banana | has("color")' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("Check for existence of color key within Banana object" & @CRLF) ConsoleWrite("Input: : " & _jqCompactPrintJson($sJson) & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF) Count of how many Items in an object
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple":{"color":"Red"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = '.Banana | length' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("How many items in the Banana object" & @CRLF) ConsoleWrite("Input: : " & _jqCompactPrintJson($sJson) & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF) How to PUT/Create/Modify JSON
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sInput = "" $sFilter = 'setpath(["Apple","color"];"Red") | setpath(["Banana","color"];"Yellow") | setpath(["Banana","season"];"Summer")' $sOptions = '-n' ;required if no input supplied $sCmdOutput = _jqExec($sInput, $sFilter, $sOptions) ConsoleWrite("Update/Create JSON" & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & @CRLF & $sCmdOutput & @CRLF) List all of the fruits (top-level keys)
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple":{"color":"Red"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = 'keys | .[]' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("List all top-level keys (fruits)" & @CRLF) ConsoleWrite("Input : " & $sJson & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & @CRLF & $sCmdOutput & @CRLF) Calculate the sum of all of the objects' price * qty
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '[{"id":1,"price":20.00,"qty":10},{"id":2,"price":15.00,"qty":20.25},{"id":3,"price":10.50,"qty":30}]' $sFilter = 'map(.price * .qty) | add' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("Calculate the sum of all of the objects' price * qty" & @CRLF) ConsoleWrite("Input : " & $sJson & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF)
      The examples above, and the ones in the example files, merely scratch the surface of what jq can do.  It may look intimidating at first but it really isn't that bad once you start playing with it.
      If you have any questions regarding the UDF, or how to perform a certain task using jq, I'll try my best to answer them.  Since jq has been around for a while now, there's also several jq-related questions and answers on StackOverflow.
      If you work with JSON, I hope you find this UDF useful as I do.
      >>> Download in the Files Section <<<
  • Create New...