Search the Community
Showing results for tags 'json'.
-
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://jqlang.github.io/jq/ jq Manual: https://jqlang.github.io/jq/manual/ jqWiki (FAQ, Cookbook, Advanced Topics) https://github.com/jqlang/jq/wiki 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. 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 is only needed if the jq executale is not in the PATH or @ScriptDir _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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. You can find several more examples and play around with them or create your own using jqPlayground. jqPlayground is a separate, stand alone, interactive tool for creating, testing and learning JSON processing using jq. 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. >>> Download the UDF in the Files Section <<<
-
Hello all, I have such JSON file (the example is simplified for demonstration, the original one can content about 20000 array blocks or even more). I need the audience help to flip the "Flip_Me" array. { "Example": { "EnableList": true, "Color": true "Flip_Me": [ { "Name": "Test_1", "Type": { "CAT": 1.1, "DOG": 1.2, "FOX": 1.3 }, "Form": { "ABC": 1.4, "CDE": 1.5, "NON": 1.6 } }, { "Name": "Test_2", "Type": { "CAT": 2.1, "DOG": 2.2, "FOX": 2.3 }, "Form": { "ABC": 2.4, "CDE": 2.5, "NON": 2.6 } }, { "Name": "Test_3", "Type": { "CAT": 3.1, "DOG": 3.2, "FOX": 3.3 }, "Form": { "ABC": 3.4, "CDE": 3.5, "NON": 3.6 } } ] } } Thanks
-
Introduction 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;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
-
Hi, I'm failing to send Curl post command using AutoIT, basically I believe that the reason is having '!' special character in URL I would be glad for help ; Construct JSON data Local $jsonData = '{"exit_status": ' & $exitStatus & ', "plugin_output": "' & $pluginOutput & '"}' ; Send CURL command Local $curlCommand = 'curl -X POST -k -H "Content-type: application/json" -H "Accept: application/json" --data "' & $jsonData & '" "https://<URL>/v1/actions/process-check-result?service=.com!passive.setEnv_check"'
-
Hello Everyone I have a strange issue ... The json generated array is not getting sorted properly for some reason #include <json.au3> #include <Array.au3> Dim $Chart[0][2] ; Array size of 2 columns $object = json_decode(FileRead("Test.json")) ;for local testing $Coins = json_get($object, '.data') for $i = 0 to UBound($Coins) -1 $name = json_get($object, '.data[' & $i & '].name' ) $change_1h = json_get($object, '.data[' & $i & '].quote.USD.percent_change_1h') _ArrayAdd($Chart,$name & "|" & number($change_1h,3) ) Next _ArraySort($Chart, 1, Default, Default, 1) _ArrayDisplay($Chart) _ArraySort is sorting the array like this (wrong): However if i click on the "Col 1" header it will be sorted correctly: How can i make _ArraySort sort them like clicking on "Col 1" does ? PS: i tried using the function "Number()" when i add the value to the array , but same result .. Thanks in advance Test.json
-
Version v1.7.4
833 downloads
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 Home Page: https://jqlang.github.io/jq/ jq Manual: https://jqlang.github.io/jq/manual/ jqWiki (FAQ, Cookbook, Advanced Topics) https://github.com/jqlang/jq/wiki 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. 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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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" ;Initialize jq environment _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. You can find several more examples and play around with them or create your own using jqPlayground. 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. -
Version v1.3.3
241 downloads
Create / Test / Learn JSON Processing jqPlayground is an interactive, jq-based, tool created using AutoIt. The purpose of the tool is to help in the creation, testing, and understanding of JSON filters/queries used in the processing of JSON datasets. Internally, it uses the jq UDF for all JSON processing. The dot and bracket notation access in jq are similar to other existing AutoIt JSON parsing UDFs and tools. Therefore, jqPlayground can be used as a general purpose testing & learning tool, regardless of the ultimate UDF or utility you choose to use. jqPlayground comes with numerous examples to help you see and understand how it can be used for simple parsing and much more advanced JSON processing. You can modify and play with the example filters or you can create and test your own. CONFIGURATION The only requirement needed to run jqPlayground is that it can find a jq executable. JQ executables can be found on the JQ website on the home page, its download section, or as a part of my JQ UDF in the AutoIt Downloads section. The latest jq executables have been included in the zip file. jqPlayground will look for the jq executable in the following order of precedence: 1. If a jqPlayground.ini file exists in the script directory, it will get the path to the jq executable under to following section and key: [CONFIG] JqExePath=<full path to jq exe> 2. A jq-win32.exe or jq-win64.exe, depending on the OS, in the script directory. 3. A jq.exe in the script directory. USAGE The interface is pretty simple and straight forward. Paste, load or write whatever JSON you want to play with in the INPUT section. Paste or write whatever parsing or processing filter(s) you want to test in the FILTER section. If necessary, you can select or enter any jq-specific flags you want. Then, either press the RUN button, F5 or CTRL+ENTER to execute your filter. You will see the output in the OUTPUT section. If your command was not successful, you will see the error message generated by JQ in the output section. There are also numerous examples that can be selected from EXAMPLES dropdown list. Upon selecting an example, it populates the filter, flags, and input as necessary. It then executes the example, showing the output in the OUTPUT section. The examples use one of 2 JSON datasets. BOOKS is a small, simple, JSON dataset that contains a catalog of book information. The NFL JSON dataset is much larger and complex. It is a snapshot of NFL game information during week 1 of the 2018 regular season. Some of the NFL JSON dataset examples really show off the speed and processing capabilities of JQ. If you want to dump the full path of every scalar JSON value in your JSON dataset, you can type "dump" in the FILTER section and press F5, CTRL+ENTER or the RUN button. The output is the same as the jqDump() function in the jq UDF. "Dump" is not a jq filter command. It is a special command that I added to help those new to JSON understand how to access a given JSON value using dot-notation. Lastly, right below the output section, you will see the time it took to execute your filter. This can be useful to those in which timimg is a major concern. jqPlayground HotKeys -------------------- Open the online jq manual - F1 Run the jq filter - F5 or Ctrl+Enter Clear/reset all fields - Alt+C Load a JSON from a file - Alt+L Save your current session - Ctrl+S Load a saved session - Ctrl+L Special Commands (Enter and run in filter) ------------------------------------------ dump - List full path of every scalar JSON value clear - Clear/reset all fields (same as Alt+C) USEFUL LINKS jq Home Page: https://jqlang.github.io/jq/ jq Manual: https://jqlang.github.io/jq/manual/ jq Downloads: https://jqlang.github.io/jq/download/ jq Tutorial: https://jqlang.github.io/jq/tutorial/ jq Wiki: https://github.com/jqlang/jq/wiki -
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')
-
Hello friends, I need help getting data from json. I read json from url into a variable. Is possible to get volume_USD value etc. where product_id= "ETH-BTC", ? So I want get "37421.69109185" as variable. I think is better keeping it in the memory as variable. Or easier to convert it to db or csv? #include <Inet.au3> #include <json.au3> $URL="https://api.abucoins.com/products/stats" $data = _INetGetSource($URL) MsgBox("","",$data) $object=json_decode($data) local $i=0 while 1 $message=json_get($object,'[product_id]');???????????????????????????????? MsgBox("","volume_USD",$message) $i=$i+1 WEnd the json structure is here: https://api.abucoins.com/products/stats [ { "product_id": "ETH-BTC", "last": "0.05202015", "open": "0.05009375", "high": "0.05250000", "low": "0.04872420", "volume": "47.77440456", "volume_BTC": 2.48523169, "volume_USD": 37421.69109185, "volume_7d": "364.40240341", "volume_30d": "3555.83377072", "change": "3.85" }, { "product_id": "LTC-BTC", "last": "0.01737490", "open": "0.01744636", "high": "0.01779000", "low": "0.01658091", "volume": "67.62762830", "volume_BTC": 1.17502328, "volume_USD": 17941.95920676, "volume_7d": "611.57893068", "volume_30d": "3881.57766044", "change": "-0.41" }, { "product_id": "ETC-BTC", "last": "0.00191846", "open": "0.00189001", "high": "0.00198000", "low": "0.00162741", "volume": "66.48327742", "volume_BTC": 0.12754551, "volume_USD": 1947.54976323, "volume_7d": "738.94495089", "volume_30d": "4090.74712156", "change": "1.51" }, { "product_id": "ZEC-BTC", "last": "0.03466163", "open": "0.03365452", "high": "0.03466163", "low": "0.03295811", "volume": "33.40101560", "volume_BTC": 1.15773364, "volume_USD": 17677.95599574, "volume_7d": "191.15953471", "volume_30d": "887.70158297", "change": "2.99" } ]
-
#include <SQLite.au3> ;-- When SQLite is compiled with the JSON1 extensions it provides builtin tools ;-- for manipulating JSON data stored in the database. ;-- This is a gist showing SQLite return query as a JSON object. ;-- https://www.sqlite.org/json1.html Example() Func Example() _SQLite_Startup() ; "<your path>\sqlite3.dll", False, 1) ; https://www.autoitscript.com/autoit3/docs/libfunctions/_SQLite_Startup.htm _SQLite_Open() ; ...if you can not run this due to errors, get the latest DLL from https://www.sqlite.org/ If _SQLite_Exec(-1, "CREATE TABLE users (id INTEGER PRIMARY KEY NOT NULL, full_name TEXT NOT NULL, email TEXT NOT NULL, created DATE NOT NULL );") Then Return 4 If _SQLite_Exec(-1, 'INSERT INTO users VALUES ' & _ '(1, "Bob McFett", "bmcfett@hunters.com", "32-01-01"),' & _ '(2, "Angus O''Vader","angus.o@destroyers.com", "02-03-04"),' & _ '(3, "Imperator Colin", "c@c.c", "01-01-01");') Then Return 5 ; -- Get query data as a JSON object using the ; -- json_group_object() [1] and json_object() [2] functions. _SQLite_GetTable2d_ArrayToConsole("SELECT" & _ " json_group_object(" & _ " email," & _ " json_object('full_name', full_name, 'created', created)" & _ " ) AS json_result" & _ " FROM (SELECT * FROM users WHERE created > ""02-01-01"");") ; {"bmcfett@hunters.com":{"full_name":"Bob McFett","created":"32-01-01"},"angus.o@destroyers.com":{"full_name":"Angus O'Vader","created":"02-03-04"}} ; -- Get query data as a JSON object using the ; -- json_group_array() function to maintain order. _SQLite_GetTable2d_ArrayToConsole("SELECT" & _ " json_group_array(" & _ " json_object('full_name', full_name, 'created', created)" & _ " ) AS my_json_result_OrAnythingReally" & _ " FROM (SELECT * FROM users ORDER BY created);") ; [{"full_name":"Imperator Colin","created":"01-01-01"},{"full_name":"Angus O'Vader","created":"02-03-04"},{"full_name":"Bob McFett","created":"32-01-01"}] ;-- Links ;-- [1] https://www.sqlite.org/json1.html#jgroupobject ;-- [2] https://www.sqlite.org/json1.html#jobj ; example found at https://gist.github.com/akehrer/481a38477dd0518ec0086ac66e38e0e2 EndFunc ;==>Example Func _SQLite_GetTable2d_ArrayToConsole($sSQL, $hDB = -1) Local $aResult, $iRows, $iColumns If _SQLite_GetTable2d($hDB, $sSQL, $aResult, $iRows, $iColumns) Then ConsoleWrite("! SQLite Error: " & _SQLite_ErrCode($hDB) & @CRLF & "! " & _SQLite_ErrMsg($hDB) & @CRLF) Else _SQLite_Display2DResult($aResult) EndIf ConsoleWrite(@CRLF) EndFunc ;==>_SQLite_GetTable2d_ArrayToConsole Based on this example, you can build your own query. The code has all the explanations. Enjoy
-
Ciao, This example reproduces the problem I encounter when sending a post request to an echo server. Instead of being sent as text utf8, the data is transmitted base64 encoded. Example: - json String: '{"firstName":"Jonathan","lastName":"Freeman","loginCount":4,"active": "yes","text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel volutpat nunc. Maecenas id tempus mi. Morbi ipsum enim, ultricies ac augue sit amet, ullamcorper finibus ex. Vestibulum vel posuere nibh, nec faucibus eros. Nam malesuada non lacus a suscipit. Nulla rhoncus tempus mi quis placerat. Curabitur commodo tincidunt justo quis sollicitudin."}' - server response: "data:application/octet-stream;base64,AAAAALgE6QNYAIAAAgAAANQCAAAAAAAAWF8AAAAAAAD0VQAAAAAAAD9APQAAAAAAAwAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAABBAAAAAAABRUAAAAmIZwcAbRt8/LMa9UAAAAAAAAAAGFzIGlkIHRlbXB1cyBtaS4gTW9yYmkgaXBzdW0gZW5pbSwgdWx0cmljaWVzIGFjIGF1Z3VlIHNpdCBhbWV0LCB1bGxhbWNvcnBlciBmaW5pYnVzIGV4LiBWZXN0aWJ1bHVtIHZlbCBwb3N1ZXJlIG5pYmgsIG5lYyBmYXVjaWJ1cyBlcm9zLiBOYW0gbWFsZXN1YWRhIG5vbiBsYWN1cyBhIHN1c2NpcGl0LiBOdWxsYSByaG9uY3VzIHRlbXB1cyBtaSBxdWlzIHBsYWNlcmF0LiBDdXJhYml0dXIgY29tbW9kbyB0aW5jaWR1bnQganVzdG8gcXVpcyBzb2xsaWNpdHVkaW4uIn0=" How can I go about transmitting data in text format utf8? Thanks in advance for the help. In the zip file: - CurlJsonPost.au3: this script - Curl.au3: UDF by Ward (thank you!) - data.json: json srting for command line test Note: using Curl.exe with json string saved in a file (utf8 encoded) named data.json, works perfectly To try with the command line tool: - save data.json in curl\bin directory - open cmd.exe and cd to curl\bin directory - Enter the following command: curl -H "Content-Type: application/json" --data @data.json https://httpbin.org/post #Include "Curl.au3" Global $_cURL_OutputBuffer Local $sJson = '{"firstName":"Jonathan","lastName":"Freeman","loginCount":4,"active": "yes","text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel volutpat nunc. Maecenas id tempus mi. Morbi ipsum enim, ultricies ac augue sit amet, ullamcorper finibus ex. Vestibulum vel posuere nibh, nec faucibus eros. Nam malesuada non lacus a suscipit. Nulla rhoncus tempus mi quis placerat. Curabitur commodo tincidunt justo quis sollicitudin."}' Local $iRetCode, $sServerResponse ConsoleWrite("=== Json post test ===" & @LF) ConsoleWrite(StringFormat("Retcode: %s - %s", $iRetCode, Curl_Easy_strerror($iRetCode)) & @LF) ConsoleWrite("Data returned from server" & @LF & @LF) $sServerResponse = JsonPost_Test($sJson, $iRetCode) ConsoleWrite($sServerResponse & @LF) Func JsonPost_Test($sJson, ByRef $iRetCode) ; Init Easy Curl Interface e set url (echo service) Local $oCurl = Curl_Easy_Init() curl_easy_setopt($oCurl, $CURLOPT_URL, "https://httpbin.org/post") ; Set content type header Local $headers = curl_slist_append(0, "Content-Type: application/json") curl_easy_setopt($oCurl, $CURLOPT_HTTPHEADER, $headers) ; Post fields & size curl_easy_setopt($oCurl, $CURLOPT_POSTFIELDS, $sJson) curl_easy_setopt($oCurl, $CURLOPT_POSTFIELDSIZE, StringLen($sJson)) ; Set callbac function to get server response back (see global var $_cURL_OutputBuffer) $hWriteFunc = DllCallbackRegister("WriteFunc_CallBack", "uint:cdecl", "ptr;uint;uint;ptr") curl_easy_setopt($oCurl, $CURLOPT_WRITEFUNCTION, DllCallbackGetPtr($hWriteFunc)) ; Ignore ssl certificates check curl_easy_setopt($oCurl, $CURLOPT_SSL_VERIFYPEER, 0) curl_easy_setopt($oCurl, $CURLOPT_SSL_VERIFYHOST, 0) ; Execute the post request $iRetCode = curl_easy_perform($oCurl) ; Set return trasfer & clear output buffer global var Local $sReturnTransfer = $_cURL_OutputBuffer $_cURL_OutputBuffer = "" Return SetError(0, 0, $sReturnTransfer) EndFunc Func WriteFunc_CallBack($ptr,$nSize,$nMemb,$pStream) Local $vData = DllStructCreate ("byte[" & $nSize*$nMemb & "]",$ptr) $_cURL_OutputBuffer &= BinaryToString(DllStructGetData($vData,1)) Return $nSize*$nMemb EndFunc curlJsonPost.zip
-
Hi AutoIters! Here is my new UDF about GUIs: it's an enhanced mixture of Advanced InputBox (deprecated) and KODA Parser (deprecated), with additional functions. What you can do with it: Parse KODA files and directly create GUIs (_GUIUtils_CreateFromKODA) Parse a simple JSON form definition to simply create advanced InputBoxes with any amount/type of input controls (_GUIUtils_CreateFromJSON) Created GUIs are returned as Scripting.Dictionary objects, and you have helper functions to access GUIs controls by their names (_GUIUtils_HWnd, _GUIUtils_CtrlID, _GUIUtils_HCtrl ...) A function that can make a GUI created from KODA/JSON (defined by it's $oForm object) and make it a modal InputDialogBox (just like InputBox, but returns all entered data as Scripting.Dictionary object) Functions are documented, and there are some examples. Consider this UDF as beta, but since I'm currently using it in a small commercial project, it should become production ready in near future. To always get the latest code version, get it from Github (more up to date than this topic). Update 04/02/2020: New simple application example Fixed focused control handling in _GUIUtils_InputDialog Reset input values before returning from _GUIUtils_InputDialog Fixed CloseOnEsc in _GUIUtils_InputDialog Fixed Input not reset Fixed all ListBox items are selected Project now on GitHub https://github.com/matwachich/autoit-guiutils/ Update 05/02/2020: Support for nodate for Date and Time input controls (pass null value) New handling of focused control _GUIUtils_InputDialog: Now, you can specify the focused control in $oInitialData by setting "controlName:focus" = True Updated documentation of _GUIUtils_InputDialog Update 07/02/2020: Bug corrected when setting Data input control Added: abillity to read a single input control New functions (_GUIUtils_GetInputs, _GUIUtils_WriteInputs), documentation completion. Readme file and screenshots on Github Page GUIUtils.zip
-
Hi all, I wasnt active in this Forum forum for Years. 😅 Since I need something with Json in AutoIt i write a little UDF to save a variable to file to read it with another language - and back. After a while until my other script grows i thought - lets integrate all variables wich is possible, because i want have arrays to. This is my first public UDF in Autoit - normaly my AutoIt scripts are quick an dirty.... - like the examples for this udf. - someone want to write nice examples? I tried to write this UDF properly, cared for processing speed, low mem consumption as possible, a short code, and a high usability without beeing very familiar with arrays. What is it for? - convert nearly all types of variables to a json string for saving it in a file or to an ini. Read it back in to a same formated variable and preserv variable types. All array types are supported with nested arrays, the only restriction is ram and array/stringsize - and time if the array is very big. You can use Filters for variable types and some other options. If anyone found a bug or any suggestions, please post it. get Json.au3 from here Json.au3 JsonVar 2019.01.25.1.zip
-
- array
- multidimensional array
-
(and 3 more)
Tagged with:
-
Hi, i'm trying to implement Imgur API functions in an AutoIt program. I successfully coded the oAuth2 Authentication and i'm testing some Imgur functions. Example : https://api.imgur.com/3/account/me/images The string received is like : {"data":[{"id":"fd6f54s","title":null,"description":null,"datetime":1574502473,"type":"image\/png","animated":false,"width":1147,"height":715,"size":53516,"views":18,"bandwidth":963288,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":"ACCOUNT","account_id":ACCOUNTID,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"d6f5sd4fsf","name":"image","link":"https:\/\/i.imgur.com\/fd6f54s.png"} I'm using JSON.au3 UDF and i don't manage to make it working : Local $Obj = Json_Decode($hRequestSSL) Local $Links = Json_Get($Obj, '["data"]["link"]') The Json_Decode sends in console : "E:\Portable\Dev\AutoIt3\IncludeP\JSON.au3" (374) : ==> Variable must be of type "Object".: Return $Object.Keys() Return $Object^ ERROR It says it's not an object or i have seen in some UDF that Json_Decode takes a string as parameter. I don't know what's wrong.
-
So I have been reading on how to use OAuth2 Service accounts(https://developers.google.com/identity/protocols/OAuth2ServiceAccount) and ran into an issue with autoit I can not solve. To keep this short to communicate to the Google API I need to use a JSON Web signature containing {Base64url encoded header}.{Base64url encoded claim set}. The Header and claim set work fine but I do not know how to convert them to a byte array using autoit. I have looked around on the forums and website but have not found anything that seems to work. Here is my code. #include-once #include <Array.au3> #include <Constants.au3> #include <Debug.au3> #include <File.au3> #include "Json.au3" #include <Process.au3> #include <ProgressConstants.au3> #include <String.au3> #include <WindowsConstants.au3> #include "WinHttp.au3" #include <UnixTime.au3> #include <StringConstants.au3> Global $UnixTime = _TimeGetStamp() $sJWTheader = '{"alg":"RS256","typ":"JWT"}' $sJWTclaimset = '{"iss":"Removed@forprivacy.com","scope":"https://www.googleapis.com/auth/spreadsheets","aud":"https://www.googleapis.com/oauth2/v4/token","exp":' & $UnixTime + 3600 & ',"iat":' & $UnixTime & '}' Local $taiData = DllStructCreate("BYTE[256]") Local $sText = _base64($sJWTheader)&'.'&_base64($sJWTclaimset) DllStructSetData($taiData, 1, StringToBinary($sText, 4)) Local $bvResult = DllStructGetData($taiData, 1) $sJWTSigature = $bvResult $sJWT = _base64($sJWTheader)&'.'&_base64($sJWTclaimset)&'.'&_base64($sJWTSigature) $POSTHeader = "Content-Type: application/x-www-form-urlencoded" $hOpen = _WinHttpOpen() $hConnect = _WinHttpConnect($hOpen, "https://www.googleapis.com/") $sRead = _WinHttpSimpleSSLRequest($hConnect, "POST", "oauth2/v4/token", Default, "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" & $sJWT) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) ConsoleWrite($sRead & @LF) The whole bytes thing is beyond with what I know about auotit. I can't tell what I need to fix.
-
You can see my script to POST json and the problem where occurs backslashes before quotations. Second problem is the apperance , there is no new lines for every new value. LOOK in attached images! You can see rest api on the screen and with id = 0 its made my postman and the rest by autoit (with backslashes) Func jsonSave() ; Make login request to server JSON POST Local $data, $request Local $obj Local $adress = 'http://35.195.249.40:3004/msg' Json_Put($Obj, ".msgName", "Point HPs") Json_Put($Obj, ".msg", "Not pointed correctly") Json_Put($Obj, ".username", "karolek890") Local $Json = Json_Encode($Obj,$JSON_UNESCAPED_SLASHES) ; WITHOUT preetier becouse it makes clashes r n and t only works in autoit $request = _httpRequestBot($adress, 'POST', $Json) ; only get login if correct then success If @error Then Exit MsgBox(0, "Error", "Open method returned @error = " & @error & " and @extended = " & @extended) Else ConsoleWrite("Data to json server posted!") EndIf EndFunc Im using this JSON UDF
-
Here's a new version of my Dump.au3 file (dirty). I've recently added support to dissect (dump) as a treeview-like view any string in the variable conforming to a strict JSON grammar, whereever said string is: as a standalone string variable or in an array or a map. AFAICT the only relaxed constraint not implemented here is that numbers in parsed JSON may have leading zeroes, although leading zeroes are forbidden in pure JSON specifications. If required it wouldn't be hard to add this constraint. @c.haslam (among others) may find it useful. Use freely. Dump.au3
-
I know how JSON works. However JSON data is typically received from web based servers. My question is: Has anyone considered to use, or currently actively using JSON as an internal data container? Internal here as in an ordinary AutoIt data type, generated, populated and manipulated within an AutoIt script, without any external data sources. The JSON and BinaryCall UDFs work well and appear the de facto defaults. Are there any thoughts on using JSON for internal variable values instead of the typical array? Also, there can be situations where such a JSON collection contains an array and it will have to be parsed using typical array functions. Currently I am working on a small project where I have to keep and use various identifiers from different sources. There are several ideas in this regard, some involving SQL child tables and arrays stored with keys (maps), which lead me to think that JSON may be a more suitable data container. It readily shrinks and stretches, allowing for dynamic data growth. JSONs ability to add new repeating data groups on the fly makes it particularly powerful and appealing. Ideas and suggestions welcome Skysnake
-
Hi all, I'm trying to create a script that runs a JSON-query and then can retrieve some variables out of the returned, decoded object using JSON.au3. I have tried some other examples on this forum, but I'm stuck at one point. My query works perfectly and gets loaded into the variable $data. Then, decoding $data to $object seems to work as well. But then I can't get the date-field out of this JSON-structure with my script. The JSON-structure returned looks like this: { "content": [ { "id": "451ec583-8f27-4926-82a3-a2d85e57a110", "createdDate": "2018-08-08T08:40:57.449004Z", "updatedDate": "2018-08-08T08:40:57.449004Z", "lastOpenedDate": "2018-08-08T08:40:57.449004Z", "date": "2018-04-26T00:00:00", "description": "X-Ray Exam", "patient": { "id": "f857238a-c75d-4760-b8d1-8f50f8f9bbfa", "createdDate": "2018-08-08T08:40:37.623976Z", "updatedDate": "2018-08-08T08:40:37.623976Z", "lastOpenedDate": "2018-08-08T08:40:37.623976Z", "name": "Fuerstonia", "birthDate": "2014-06-08", "breed": "", "chip": "", "color": "", "damsire": "", "sire": "", "neutered": false, "orthancUuid": "", "sex": "U", "species": "Paard", "ueln": "De 431310762114", "pmsReference": "", "origin": "" }, "type": "study", "accessionNumber": "KME201806960467", "instanceUid": null, "orthancUuid": "", "sent": false, "seriesCount": 0, "modalityType": "RX", "typeAndModality": "study RX", "client": { "id": "be627195-8458-4927-8446-f1ef37b917a4", "createdDate": "2018-08-08T08:40:31.433968Z", "updatedDate": "2018-08-08T08:40:31.433968Z", "lastOpenedDate": "2018-08-08T09:26:49.512298Z", "via": "", "extraInfo": "", "pmsReference": "", "contact": { "id": "406cc555-c491-4c29-b6bb-8d903f0e35a9", "createdDate": "2018-08-08T08:40:31.428968Z", "updatedDate": "2018-08-08T08:40:31.428968Z", "lastName": "Client 1", "firstName": "", "company": "", "email": "", "language": "nl", "phone": "", "address": { "id": "6fc7703c-137a-4e0a-ba96-8c7f38f2044b", "city": "", "country": "", "line": "", "postalCode": "" } } } }, My script looks like this: #RequireAdmin #include <json.au3> #include <inet.au3> #include <File.au3> ;Create a handle to a logfile (will be created if it doesnt exist) Global $logfile = FileOpen("C:\VSOL\VSTK\Logs\MigrationFix\MigrationFix.log",9) FileWriteLine($logfile,"Start script") ;Create the URL with the JSON-query $URL = "http://localhost:8080/v0/studies/?seriesCount=1" ;Catch the query output into a variable $data = _INetGetSource($URL) ;Check if there is any data at all in this variable, if not, exit If Not $data Then MsgBox(1,"Error","No answer. Server is probably not running.") Exit EndIf ;For debugging purposes FileWriteLine($logfile,$data) ;Decode the JSON_string into a useable object $object = Json_Decode($data,1000) If @error Then FileWriteLine($logfile,"Error decoding JSON") Exit EndIf Local $i = 0 ;Start a loop to retrieve the study date of each study... While 1 $study_date = json_get($object,'[' & $i & '].date') If @error Then FileWriteLine($logfile,"Study-Date retrieval error") ExitLoop EndIf $i = $i + 1 WEnd ;Close the logfile FileWriteLine($logfile,"Stop script") FileClose($logfile) ;Open the logfile for quick reference ShellExecute("C:\VSOL\VSTK\Logs\MigrationFix\MigrationFix.log") If believe it has something to do with my json_get($object...)-command. Anyone who can point me in the right direction? Thanks in advance! Kind regards
-
Hello there, since I spent some time to access the REST-API of the web shop system Shopware, I'd like to share a few lines to make life easier for others. With this you can access your Shopware database, reading and writing all kind of data. Replies are JSON style. To work with JSON I usually depend on either just own AutoIt string operations or this AutoIt library: ; File : Json.au3 (2015.01.08) ; Purpose : A Non-Strict JavaScript Object Notation (JSON) Parser UDF ; Author : Ward $UserName="xxxx" ;Shopware credentials of Shopware user who has the API checkbox ticked $PassWord="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ;API-Key of this user, NOT the Password $URL="www.XXX.com/api/" $Command="orders/64682?useNumberAsId=true" ;A list of commands and options is available through shopware REST-API help; Here we read order number 64682 $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "https://" & $URL & $Command , False) $oHTTP.SetCredentials($UserName, $PassWord, 0) $oHTTP.Send() $response = $oHTTP.ResponseText ConsoleWrite ($response & @CRLF & @CRLF)
-
hi guys ! how are you ? fine ? yeahhh Here is my problem: I have 2 autoit applications, a.exe and b.exe In a.exe, i call b.exe with a json as parameter: FileWrite("N:\+++ Dev\ClientServeur\FolderMonitor.nca", "lejson in A:" & Json_Encode($json_tmp)& @CRLF) Run(@ScriptDir & "\FolderMonitor.exe " & Json_Encode($json_tmp) ) In program B: ;Firstline of program: FileWrite("N:\+++ Dev\ClientServeur\FolderMonitor.nca", @CRLF & "json in B:" & $CmdLine[1] & @CRLF) Output: lejson in A:{"DOSSIERS":{"Dossier_Hidden":"N:\\+++ Dev\\ClientServeur\\","Dossier_du_script":"N:\\+++ Dev\\ClientServeur\\","Fichier_Historique":"N:\\+++ Dev\\ClientServeur\\Historique.log","Fichier_DEBUG":"N:\\+++ Dev\\ClientServeur\\FolderMonitor.nca"}} json in B :{DOSSIERS:{Dossier_Hidden:N:\\+++ Dev\\ClientServeur\\,Dossier_du_script:N:\\+++ Dev\\ClientServeur\\,Fichier_Historique:N:\\+++ Dev\\ClientServeur\\Historique.log,Fichier_DEBUG:N:\\+++ Dev\\ClientServeur\\FolderMonitor.nca}} As you see, i lost my quote in my json so it's au problem to parse my json. I use THIS library I tried different type of encoding (ex JSON_STRICT_PRINT), but i don't think that it's the problem. Maybe i'm wrong thanks Nicolas.
-
Hello. I have a program that has used ADO database connection to return a query and then subsequently put the query results into an array using getrows. See snippet below: $constrim="DRIVER={SQL Server};SERVER=xxx-xxxxx\CSC;DATABASE=xxxxxxxxx;uid=xxxxxxxxxx;pwd=xxxxxxxxxxxx;" $adCN = ObjCreate ("ADODB.Connection") ; <== Create SQL connection $adCN.Open ($constrim) ; local $sQuery = "select * from tbl_Apps" ; get all applications in the database local $oAppRecordSet = $adCN.Execute($sQuery) local $aAppsInDB = $oAppRecordSet.Getrows(5000) With the code above I can perform array operations very efficiently. Now I need to get this data via JSON which is working (using Ward's JSON UDF) but the data set returned is large (approx 4MB) and I'm wondering what is the most efficient way to get this data into an array. Dim $obj = ObjCreate ("WinHttp.WinHttpRequest.5.1") $obj.Open("GET", $URL, false) $obj.SetRequestHeader("Content-Type", "application/json") $obj.Send() $json = JSON_decode( $obj.ResponseText ) Any help would be appreciated!!
-
Hi This UDF is for anyone who - Object Orientated Programing ie properties and methods in autoIT - needs standards compliant JSON,, - JSON.parse (read) and JSON.stringify (to text ) - Now JSONPath - wants to use dot syntax in AutoIT like you would in Javascript - dosen't like AutoIt arrays - full javascript arrays and objects in AutoIT! - knows javascript or would like to learn autoIT or vice versa. - call javascript functions like EncodeURI - run any javascript from autoIT ! Tested IE8 - IE11. v7 JSON_OO v7.zip - IE free version. ( hey microsoft ditched IE now too!) .- No IE dependencies- Added arrayAdd and arrayDel- JSONPath! for searching.- Added Keys Function - to list properties of a JSON object.- Secure JSON parse- Native Pure JS implementaion not a port.Credits to Douglas Crockford's for JSON2 code and stefan.goessner for JSONPath code. (see example file). v4 - json_oo_v4.zip. - use v7 (v4 may not work because of windows updates on dec-2014. ). v4 uses IEs JSON , so no ported external librariesv4 also includes a Non - IE version of JSON no include files but no stringify and uses javascript EVal (not secure). use v7.eg valid JSON '{ "hello" : "world" }' invalid "{ 'hello' : 'world' }"v4 does not have JSONPath , arrayAdd, arrayDel or keys (properties) methods - use v7 - enjoy ...the brakes come off Autoit . This is the smallest OO extensions for AutoIT Object Oriented JSON --- using JSON to Build Objects in Native AutoIT -- Using JSON to create objects $oJSON = _OO_JSON_Init ( ) $jsObj = $oJSON.parse('{ "hello": "world" }') $jsObj.hello;-> world $oJSON.stringify( $jsObj );-> {"hello":"world"} $jsObj.stringify();-> {"hello":"world"} ARRAYS - goodbye Auto it arrays hooray The real magic in this script is that it lets you access JSON array items by index number through dot syntax without the need for a for-each loop. eg you can go $obj.arr.item(n) It does this by making javascript objects syntax friendly to Autoit. . Also you can go $obj.arr.item("property").and $obj.arr.property & Also $obj.arr.length (see below) -- Using JSON to create one dimentional array $sJSON=[ "h1", "h2", "h3" ] $oResult.length= 3 $oResult.item(0);-> h1 -- Using JSON to create 2 dimentional array; $sJSON=[[1,2],[3,4],[5,6]] $oResult.length= 3 $oResult.item(0);-> $oResult.item(0).stringify();-> [1,2] $oResult.item(2).item(1);-> 6 $oResult.item(2).length;-> 2 -- Using JSON to create an object array $sJSON= [ { "card":"ace" }, {"card":"king" }] $oResult.length= 2 $oResult.item(0).card;-> ace -- Using JSON to create key values $sJSON= { "name":"Jon" , "surname":"who" } $oResult.item("surname");-> who $oResult.surname ;-> who Many other benefits such as building objects using JSON text just like you would in JavaScript Basic OO - Properties and methods -- Add properties to objects in AutoIT $jsObj.propAdd("myProp", "'x'") $jsObj.myProp ;-> x $jsObj.propAdd("myProp", '{ "hello": "world" }') $jsObj.myProp.hello ;-> world -- User Defined methods - using javascript -CASE SENSITIVE $jsObj.methAdd("myMethod", " Function('y','return y*5') " ) $jsObj.myMethod(5) ;-> 25 Some people have problems on 64 bit autoIT windows with the script control...here is the work around.. '?do=embed' frameborder='0' data-embedContent>> You will most likely have the script control ..but here it is.. http://www.microsoft.com/en-us/download/details.aspx?id=1949 --- using JSON to Build Objects in Native AutoIT -- Using JSON to create objects $oJSON = _OO_JSON_Init ( ) $jsObj = $oJSON.parse('{ "hello": "world" }') -- Accessing Items $jsObj.hello;-> world $jsObj.item("hello");-> world -- Using Any Object to create objects $jsObj.stringify();-> {"hello":"world"} $jsObj = $jsObj.parse('{ "goodbye": "world" }') $jsObj.goodbye;-> world -- Read JSON from a file (PC only) - untested $var = _OO_JSON_Read_File("jsondata.txt") $obj = $oJSON.parse($var) > BASIC OO (Object Oriented) programming in Auto it -- Compound Syntax $oJSON.parse( '{ "hello":"world" }' ).hello;-> world -- assigning propeprties $jsObj.parse ( '{ "goodbye": "world" }') $jsObj.goodbye ;-> world $jsObj.goodbye = "hello" $jsObj.goodbye;-> hello > OO Adding Methods and Properties in Auto it -- Add properties to objects in AutoIT $jsObj.propAdd("myProp", "'x'") $jsObj.myProp ;-> x $jsObj.propAdd("myProp", '{ "hello": "world" }') $jsObj.myProp.hello ;-> world -- User Defined methods - using javascript -CASE SENSITIVE $jsObj.methAdd("myMethod", " Function('y','return y*5') " ) $jsObj.myMethod(5) ;-> 25 > Querying Objects $jsObj = $oJSON.parse('{ "hello": "world" , "Goodbye" : "World" } ') $jsObj.type($jsObj) ->object $jsObj.isArray() ->False -- List object properties or "keys" $jsObj.keys($jsObj).stringify() ->["hello","Goodbye"] -- Querying Objects $jsObj = $jsObj.parse({ "hello" : "world" , "myarray" : [ "item0", 2 , { "jon" : "who"} ] }) > JSON path - always returns an array of matches $jsObj.jsonPath( "$.*").stringify() -> ["world",["item0",2,{"jon":"who"}]] $jsObj.jsonPath( "$..hello").stringify() -> ["world"] $jsObj.jsonPath( "$..myarray").stringify() ->[["item0",2,{"jon":"who"}]] $jsObj.jsonPath( "$..myarray[?(@.jon)]").stringify() ->[{"jon":"who"}] $jsObj.jsonPath( "$..myarray[?(@.jon)]").item(0).stringify() ->{"jon":"who"} > Basic Arrays using JSON -- Querying Arrays $jsObj.myarray.stringify() ->["item0",2,{"jon":"who"}] $jsObj.type($jsObj.myarray) ->object $jsObj.myarray.isArray() ->True $jsObj.myarray.length ->3 $jsObj.type($jsObj.myarray.item(0)) ->string $jsObj.type($jsObj.myarray.item(1)) ->number $jsObj.type($jsObj.myarray.item(2)) ->object > Modifying Arrays using OO -- Empty array; $jsObj = $oJSON.parse('[]') $jsObj.stringify() ->[] $jsObj.isArray( ) ->True -- Add items; $jsObj.arrayAdd( 0, "test0") $jsObj.arrayAdd( 1, "test1") $jsObj2 = $oJSON.parse( '{ "hello" : "world" }') $jsObj.arrayAdd( 2, $jsObj2) $jsObj.stringify() ->["test0","test1",{"hello":"world"}] -- Delete items; $jsObj.arrayDel( 0) $jsObj.stringify() ->["test1",{"hello":"world"}] -- Using JSON to create one dimentional array $sJSON=[ "h1", "h2", "h3" ] $oResult.length= 3 $oResult.item(0);-> h1 -- Using JSON to create 2 dimentional array; $sJSON=[[1,2],[3,4],[5,6]] $oResult.length= 3 $oResult.item(0);-> $oResult.item(0).stringify();-> [1,2] $oResult.item(2).item(1);-> 6 $oResult.item(2).length;-> 2 -- Using JSON to create an object array $sJSON= [ { "card":"ace" }, {"card":"king" }] $oResult.length= 2 $oResult.item(0).card;-> ace -- Using JSON to create key values $sJSON= { "name":"Jon" , "surname":"who" } $oResult.item("surname");-> who $oResult.surname ;-> who > Working with OO Objects -- assigning JSON objects in AutoIT $jsObj = $oJSON.parse( '{ "hello" : "world" }') $jsObj2 = $oJSON.parse( '{}' ) $jsObj2 = $jsObj $jsObj.hello;-> world $jsObj2.hello;-> world -- Assign an JSON object to a property $jsObj = $oJSON.parse( '{ "hello" : "world" }') $jsObj.hello ;-> world $jsObj2.propAdd("myProp") $jsObj2.myProp = $jsObj $jsObj2.myProp ;-> $jsObj2.myProp.stringify() ;-> {"hello":"world"} $jsObj2.myProp.hello ;-> world -- Using Existing JS Objects , Object must exist in the scripting object (not IE) $oJSON2 =$jsObj.objGet('JSON') ; objGet is javascript eval $oResult = $oJSON2.parse('{ "hello":"world" }') $oResult.hello;-> world > Using Javascript functions extending UDF -- Calling javascript standard functions $jsObj.jsFunAdd( "encodeURI") $jsObj.encodeURI( 'te st' );-> te%20st $jsObj.protoAdd("encodeURI", " function (s) { return encodeURI(s); } " $jsObj.encodeURI( 'te st' );-> te%20st -- Calling javascript literal methods $str_obj = $jsObj.toObj("my string") $str_obj.jsMethAdd( "charAt") $str_obj.charAt( 0 );-> m $jsObj.toObj('\"my string').charAt(0) ;-> \ $str_obj.jsFunAdd( "charAt") $str_obj.charAt( 0 );-> m $jsObj.jsMethAdd("toFixed" ) $jsObj.toObj(5.56789).toFixed(2) ;-> 5.57 $jsObj.jsMethAdd("concat" , 3 ) $jsObj.toObj('hello').concat( ' world', ' again ', ' and again ' ) ;-> hello world again and again $jsObj.dot("\""'my string", "charAt(0)" );-> \ > depreciated syntax -- depreciated syntax - previous UDFs $jsObj = _JS_obj_create ( '{ "hello": "world" }') ; invalid "{ 'hello':'world'}" $jsObj.hello ;-> world $jsObj.objToString();-> {"hello":"world"} $jsObj.strToObject ( '{ "goodbye": "world" }') $jsObj.goodbye ;-> world -- Close IE explorer.exe instance - not required anymore _OO_JSON_Quit ( ) -- Objects still usable after _OO_JSON_Quit closes $jsObj.goodbye ;-> world Example script output; see example file ; enjoy
- 49 replies
-
- javascript
- json
-
(and 3 more)
Tagged with:
-
[ [ [ "Kinh Oanh,\r\n", "Dear Oanh,\r\n", null, null, 3 ], [ "C\u1ea3m \u01a1n b\u1ea1n r\u1ea5t nhi\u1ec1u v졢\u1ee9c th\u01b0 c\u1ee7a b\u1ea1n \u0111\u1ebfn m\u1ed9t v᩠ngṠtr\u01b0\u1edbc. ", "Thank you very much for your letter which arrived a few days ago.", null, null, 3 ], [ "Th\u1eadt \u0111⯧ y뵠khi nghe t\u1eeb b\u1ea1n.\r\n", "It was lovely to hear from you.\r\n", null, null, 3 ], [ "b\u1ea1n \u0111i \u0111㵠v\u1eady.\r\n", "where do you go.\r\n", null, null, 1 ], [ "T\u1ea1m bi\u1ec7t!", "Goodbye!", null, null, 1 ] ], null, "en", null, null, null, 0.91366601, null, [ [ "en" ], null, [ 0.91366601 ], [ "en" ] ] ] How to parse array to json?
-
I'm trying to get an array from a website so that I can just get the url, but I am not sure how. I read a bit of arrays but I have a feeling I'd have to be writing a lot more than what I should be. I will include the script I have so far and the API url for what I want. API: https://api.fast.com/netflix/speedtest?https=true&token=YXNkZmFzZGxmbnNkYWZoYXNkZmhrYWxm&urlCount=1 (I want the 'url' array that contains the url) Code: #include <MsgBoxConstants.au3> #include <Inet.au3> #include <Array.au3> $site = _INetGetSource('http://api.fast.com/netflix/speedtest?https=true&token=YXNkZmFzZGxmbnNkYWZoYXNkZmhrYWxm&urlCount=1') MsgBox($MB_SYSTEMMODAL, "Title", $site[1])