Jump to content
Ward

A Non-Strict JSON UDF (JSMN)

Recommended Posts

Implementation of the JSMN using Map available in Autoit Beta (3.3.15):

 

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Version=Beta
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****


#include "jsonMap.au3"

$json = '{"test":"yay"}'
$test = Json_Decode($json)
ConsoleWrite($test['test'] & @CRLF)

$test['test'] = 'horray!!!'
ConsoleWrite($test['test'] & @CRLF)

ConsoleWrite(Json_Encode($test) & @CRLF)

 

 

jsonMap.au3

Edited by dexto
Fixed a bug in the Json_Encode_Pretty()

Share this post


Link to post
Share on other sites

Edit of my answer on the importance of simple and double quote.

Quote

$akeys = Json_ObjGetKeys($JsoEqpt)

    Json_Get($JsoEqpt, '["' & $akeys[0] & '"]["tagInge"]')        => OK  Key between Double quotes:   '   [   "   '   & $akeys
    Json_Get($JsoEqpt, '["' & $akeys[0] & "']['tagInge']")        => Not OK, key between simple quotes    "   [   '   "   & $akeys

    I must indicate that my keys are Numbers only overwise i think it's ok with string key!

 

 

 

 

Share this post


Link to post
Share on other sites

hi guys !!! how are you ? fine ? nice !!!

does anyone has encountered problems, using several Json ?

I encounter a problem, i just can't success in creating a simple example to show you but i can show you a part of it :'(

Context: in my code i use 2 json, the final one, and the other is for temporary use, (in a loop and clear).

The deal is to create an array of object and add it to my json. It's ok but an array is modified when i modifiy the other... i'm going crazy...:mad:

 

I m gonna show you state of my 2 json, a jsonclear of the first one, and the second is affected too..(it change !)

 

Sorry again not giving usable example... but maybe this will gave you ideas...

Problem just with adding something to a json, the other is affected.

ConsoleWrite("Just any text to show you this is the good part of the code..." & @crlf)
                            ConsoleWrite("$JsonPopupEqpt:" & json_encode($JsonPopupEqpt) & @CRLF)
                            ConsoleWrite("$Jsontemporaire:" & json_encode($Jsontemporaire) & @CRLF)
                            ConsoleWrite("$aema:" & $aema & @CRLF )
                            ConsoleWrite("$letexte:" & $letexte & @CRLF )
                            Json_Put($Jsontemporaire, '["AEMA"]', $aema)
                            Json_Put($Jsontemporaire, '["NumeroSerie"]', $letexte)
                            ConsoleWrite("has Json_Popup_Eqpt change ?:" &json_encode($JsonPopupEqpt) & @CRLF  )
                            ConsoleWrite("Just any text  blablabla" & @crlf)

Console output:

Spoiler

Just any text to show you this is the good part of the code...
$JsonPopupEqpt:{"ListeAEMA_NS_Depose":[],"ListeAEMA":"","ListeNS":"","ListeAEMA_NS_Reprise":[{"AEMA":"AEMARAD00040","NumeroSerie":"1625004894"}],"Mouvement":"Remplacement"}
$Jsontemporaire:{"AEMA":"AEMARAD00040","NumeroSerie":"1625004894"}
$aema:AEMANBE00200
$letexte:F207420006029
has Json_Popup_Eqpt change ?:{"ListeAEMA_NS_Depose":[],"ListeAEMA":"","ListeNS":"","ListeAEMA_NS_Reprise":[{"AEMA":"AEMANBE00200","NumeroSerie":"F207420006029"}],"Mouvement":"Remplacement"}
Just any text  blablabla

 

Please note that the JsonPopupEqpt is not the same, i just don't touch it.

 

Problem just with an Objclear the other json is affected.

ConsoleWrite("Just any text to show you this is the good part of the code..." & @crlf)
                            ConsoleWrite("$JsonPopupEqpt:" & json_encode($JsonPopupEqpt) & @CRLF)
                            ConsoleWrite("$Jsontemporaire:" & json_encode($Jsontemporaire) & @CRLF)
                            ConsoleWrite("$aema:" & $aema & @CRLF )
                            ConsoleWrite("$letexte:" & $letexte & @CRLF )
                            Json_ObjClear($Jsontemporaire)
                            ConsoleWrite("has Json_Popup_Eqpt change ?:" &json_encode($JsonPopupEqpt) & @CRLF  )
                            ConsoleWrite("$Jsontemporaire:" & json_encode($Jsontemporaire) & @CRLF)
                            ConsoleWrite("Just any text  blablabla" & @crlf)

 

Console output:

Spoiler

Just any text to show you this is the good part of the code...
$JsonPopupEqpt:{"ListeAEMA_NS_Depose":[],"ListeAEMA":"","ListeNS":"","ListeAEMA_NS_Reprise":[{"AEMA":"AEMARAD00040","NumeroSerie":"1625004894"}],"Mouvement":"Remplacement"}
$Jsontemporaire:{"AEMA":"AEMARAD00040","NumeroSerie":"1625004894"}
$aema:AEMANBE00200
$letexte:F207420006029
has Json_Popup_Eqpt change ?:{"ListeAEMA_NS_Depose":[],"ListeAEMA":"","ListeNS":"","ListeAEMA_NS_Reprise":[{}],"Mouvement":"Remplacement"}
$Jsontemporaire:{}
Just any text  blablabla

Note that my json JsonPopupEqpt has it field ListeAEMA_NS_Reprise reset.... d'ont know why

They are all created with

local $JsonPopupEqpt
    If Json_IsObject($JsonPopupEqpt) Then
        Json_ObjClear($JsonPopupEqpt)
    Else
        $JsonPopupEqpt = Json_ObjCreate()
    EndIf

I've tried, renaming the jsons, (in case there are the same name is the udf), i removed the initial '_' in the name...

I'm running out of ideas...

 

I give you poor information, and no example to test, i'm sorry for that... i can't reproduce in a standalone program.

So i just ask for ideas... thanks for your comprehension

Nicolas.

Edited by satanico64
correct errors

Share this post


Link to post
Share on other sites

hi, and thanks for your answer, everything help :)

 

For sure i modify an object, it's what i want.

The 2 objects i show in my example are different ( but with same fields/type ) but i modify the first ,one the second is modified too...

I thing there is something wrong with the format. I got the problem if i modify the object, and even if i clear the object.

 

Format of my json is: { Array1 [ object, object, object...] , Array2 [ object, object, object...] }

I thing something goes wrong using array of objects, or maybe the fact i had initialised an empty array in my json

 

Indeed, i just bypass the problem using notation and only one Json::)

i just erased all, and totally rewrite...

something like:

local $JsonPopupEqpt
    If Json_IsObject($JsonPopupEqpt) Then
        Json_ObjClear($JsonPopupEqpt)
    Else
        $JsonPopupEqpt = Json_ObjCreate()
    EndIf

    Json_Put($JsonPopupEqpt, ".ListeAEMA_NS_Reprise[0].AEMA", $aema)
    Json_Put($JsonPopupEqpt, ".ListeAEMA_NS_Reprise[0].NumeroSerie", $ns)    
    Json_Put($JsonPopupEqpt, ".ListeNS", $ListeNS)
    
    ; my loop has disappear and is replaced now by: 
     $i = UBound(Json_Get($JsonPopupEqpt,".ListeAEMA_NS_Depose") )
        Json_Put($JsonPopupEqpt, ".ListeAEMA_NS_Depose[" & $i & "].AEMA", $aema)
        Json_Put($JsonPopupEqpt, ".ListeAEMA_NS_Depose[" & $i & "].NumeroSerie", $letexte)

code shorter, cleaner and it works.

Do you know any tip to get array size in the json ?

i use  $i = UBound(Json_Get($JsonPopupEqpt,".ListeAEMA_NS_Depose") )  , it works but maybe there's a different way...

 

Thanks

Nicolas

Share this post


Link to post
Share on other sites

Hi Ward

The keys of type "integer" or of type "string" are allowed in Map variable (Autoit) (as well as in scripting dictionary), and are not the same.
The Json encoding results in a change of type of keys, type "integer".
Example:

#include <Array.au3>
#include "JsonMap.au3"

ConsoleWrite("======================== MAP ===========================" & @CRLF)
;-- Tableau 2D à include dans la Map --
    Global $aTest1[2] = ['ROUGE', 'VIOLET']

    Global $Map[], $MapOut
    $Map["Cle1"] = "DataCle1"
    $Map["Cle2"] = "DataCle2"
    $Map["2"] = "DataCleString"
    $Map[2] = "DataCleNum"
    $Map["Cle3"] = $aTest1

    Global $code = Json_Encode($Map)
    ConsoleWrite('Map     Code: ' & $code & @CRLF)

    $MapOut = Json_Decode($code)

    ;-- Affichages -------------------------------
    Global $aKeys = MapKeys ($MapOut)
;~  _ArrayDisplay ($aKeys)
    ConsoleWrite("Type Cle1 = " & VarGetType($aKeys[0]) & @CRLF)
    ConsoleWrite("Type Cle2 = " & VarGetType($aKeys[1]) & @CRLF)
    ConsoleWrite('Type "2" = ' & VarGetType($aKeys["2"]) & @CRLF)
    ConsoleWrite("Type 2 = " & VarGetType($aKeys[2]) & @CRLF)

    ConsoleWrite("$MapOut[Cle1]= " & $MapOut["Cle1"] & @CRLF)
    ConsoleWrite("$MapOut[Cle2]= " & $MapOut["Cle2"] & @CRLF)
    ConsoleWrite('$MapOut["2"]= ' & $MapOut["2"] & @CRLF)
    ConsoleWrite("$MapOut[2]= " & $MapOut[2] & @CRLF)
;~  _ArrayDisplay($MapOut["Cle3"])

    ;-- Nouveau codage du résultat ----------
    Global $codeOut = Json_Encode($MapOut)
    ConsoleWrite('MapOut     Code: ' & $codeOut & @CRLF)

    ;-- comparaison des codes ---------------
    If $codeOut = $code Then
        ConsoleWrite("$codeOut = $code" & @CRLF)
    Else
        ConsoleWrite("$codeOut <> $code" & @CRLF)
    EndIf

result:

Spoiler

======================== MAP ===========================
Map     Code: {"Cle1":"DataCle1","Cle2":"DataCle2","2":"DataCleString","2":"DataCleNum","Cle3":["ROUGE","VIOLET"]}
Type Cle1 = String
Type Cle2 = String
Type "2" = String
Type 2 = String
$MapOut[Cle1]= DataCle1
$MapOut[Cle2]= DataCle2
$MapOut["2"]= DataCleNum
$MapOut[2]=
MapOut     Code: {"Cle1":"DataCle1","Cle2":"DataCle2","2":"DataCleNum","Cle3":["ROUGE","VIOLET"]}
$codeOut <> $code

Kind regards.

Edited by MimiOne

Share this post


Link to post
Share on other sites

Hi. I can not get value of 'dst' attr from JSON:

{"trans_result":{"from":"en","to":"zh","domain":"all","type":2,"status":0,"data":[{"dst":"\u6d4b\u8bd5","src":"test","relation":[],"result":[[0,"\u6d4b\u8bd5",["0|4"],[],["0|4"],["0|6"]]]}],"phonetic":[{"src_str":"\u6d4b","trg_str":"c\u00e8"},{"src_str":"\u8bd5","trg_str":"sh\u00ec"}]}}

This is table:

$aJSON['trans_result']['data']

But

$aJSON['trans_result']['data'][0]

gives an error message: Array variable has incorrect number of subscripts or subscript dimension range exceeded.

 

Share this post


Link to post
Share on other sites

My func:

Func _URIEncode($sData)
    Local $aData = StringSplit(BinaryToString(StringToBinary($sData, 4), 1), "")
    Local $nChar
    $sData = ""
    For $i = 1 To $aData[0]
        $nChar = Asc($aData[$i])
        Switch $nChar
            Case 45, 46, 48 To 57, 65 To 90, 95, 97 To 122, 126
                $sData &= $aData[$i]
            Case 32
                $sData &= "+"
            Case Else
                $sData &= "%" & Hex($nChar, 2)
        EndSwitch
    Next
    Return $sData
EndFunc   ;==>_URIEncode
Func _GetTranslateBaidu($sText)
    Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
    $oHTTP.Open("Post", "http://translate.baidu.com/v2transapi", False)
    $oHTTP.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
    $oHTTP.SetRequestHeader("Host", 'translate.baidu.com')
    $oHTTP.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")
    $oHTTP.SetRequestHeader("Connection", "keep-alive")

    ConsoleWrite('from=en&to=zh&query=' & _URIEncode($sText) & '&transtype=translang&simple_means_flag=3' & @CRLF)

    $oHTTP.Send('from=en&to=zh&query=' & _URIEncode($sText) & '&transtype=translang&simple_means_flag=3')
    If ($oHTTP.Status == 200) Then
        $sJSON = $oHTTP.ResponseText
        $aJSON = Json_Decode($sJSON, 10000)
        ConsoleWrite($aJSON['trans_result']['data'][0]['dst'] & @CRLF)
    EndIf
EndFunc   ;==>_GetTranslateBaidu

Include: jsonMap.au3

Edited by AMSPeople

Share this post


Link to post
Share on other sites

You can do this:

Local $oJson = Json_Decode($sJson)
Local $dst=Json_Get($oJson,'["trans_result"]["data"][0]["dst"]')

Saludos

Share this post


Link to post
Share on other sites

 

 error: Json_Get(): undefined function.

I use jsonMap:

Udf from the first post can not be downloaded.

I found in another location JSON.au3 library from ward.

There was another question. Can I somehow know the number of elements inside the element ["trans_result"] ["data"]?
Since variants are possible ["trans_result"] ["data"] [0] ["dst"], ["trans_result"] ["data"] [1] ["dst"], ["trans_result"] ["data "] [2] [" dst "] and so on.

 

$oJSON = Json_Decode($sJSON)
        Local $aLines = Json_Get($oJSON, '["trans_result"]["data"]')
        For $i = 0 To UBound($aLines) - 1
            $sDst = Json_Get($oJSON, '["trans_result"]["data"][' & $i & ']["dst"]')

            MsgBox(0, '', $sDst)
            ConsoleWrite($sDst & @CRLF)
        Next

 

Edited by AMSPeople

Share this post


Link to post
Share on other sites
13 hours ago, AMSPeople said:

Hi. I can not get value of 'dst' attr from JSON:

{"trans_result":{"from":"en","to":"zh","domain":"all","type":2,"status":0,"data":[{"dst":"\u6d4b\u8bd5","src":"test","relation":[],"result":[[0,"\u6d4b\u8bd5",["0|4"],[],["0|4"],["0|6"]]]}],"phonetic":[{"src_str":"\u6d4b","trg_str":"c\u00e8"},{"src_str":"\u8bd5","trg_str":"sh\u00ec"}]}}

This is table:

$aJSON['trans_result']['data']

But

$aJSON['trans_result']['data'][0]

gives an error message: Array variable has incorrect number of subscripts or subscript dimension range exceeded.

 

 

 

So it is also easy with jsonMap :)

Global $sString = '{"trans_result":{"from":"en","to":"zh","domain":"all","type":2,"status":0,"data":[{"dst":"\u6d4b\u8bd5","src":"test","relation":[],"result":[[0,"\u6d4b\u8bd5",["0|4"],[],["0|4"],["0|6"]]]}],"phonetic":[{"src_str":"\u6d4b","trg_str":"c\u00e8"},{"src_str":"\u8bd5","trg_str":"sh\u00ec"}]}}'
Global $mMap = Json_Decode($sString)
Global $aArray = $mMap.trans_result.data
Global $mData = $aArray[0]

ConsoleWrite($mData.dst & @CRLF)

 

Edited by Taz77

Share this post


Link to post
Share on other sites

How do you get a count of elements within an array? Json_ObjGetCount doesn't seem to be it.

#Include "JSon.au3"

Local $Json = '{"name":"John","cars":[ "Ford", "BMW", "Fiat", "Chevy" ]}'

;Correctly returns a count of 2 elements (name and cars)
Local $Obj = JSon_Decode($Json)
ConsoleWrite("count root: " & Json_ObjGetCount($Obj) & @CRLF) 

;Returns error Variable must be of type "Object"
Local $Cars = Json_ObjGet($Obj, '["cars"][0]')
ConsoleWrite("count cars: " & Json_ObjGetCount($aCars) & @CRLF)

Or is the only way to first loop through the array and make my own counter, then go back through and reference what I want to do?

Share this post


Link to post
Share on other sites

@Decibel Use Ubound($aCars) to get count of an array.


A cross-platform implementation of the AutoIt language

My contributions to the AutoIt Community ##AutoIt at freenode, real-time chat

3fHNZJ.gif

Spoiler

If I have hurt or offended you in anyway, Please accept my apologies, I never (regardless of the situation) intend to do that to anybody.

Share this post


Link to post
Share on other sites
On 10/12/2017 at 11:15 PM, TheDcoder said:

@Decibel Use Ubound($aCars) to get count of an array.

Thanks. I didn't realize that the JSON Arrays were "just arrays." Solution provided below for others.

#Include "JSon.au3"
    
    Local $Json = '{"name":"John","cars":[ "Ford", "BMW", "Fiat", "Chevy" ]}'

    ;Correctly returns a count of 2 elements (name and cars)
    Local $Obj = JSon_Decode($Json)
    ConsoleWrite("count root: " & Json_ObjGetCount($Obj) & @CRLF)

    ;Returns error Variable must be of type "Object"
    ;Local $Cars = Json_ObjGet($Obj, '["cars"][0]')
    ;ConsoleWrite("count cars: " & Json_ObjGetCount($aCars) & @CRLF)

    ;Solution from TheDcoder
    Local $aCars = Json_Get($Obj, '["cars"]')
    ConsoleWrite("count cars: " & UBound($aCars) & @CRLF)
    
    ;Walking the array
    For $iCurrentCar = 0 To UBound($aCars) - 1 ;zero-based array
        ConsoleWrite("Car '" & $iCurrentCar & "' of '" & UBound($aCars) & "' is '" & _
            Json_Get($Obj, '["cars"][' & $iCurrentCar & ']') & "'" & @CRLF)
    Next

 

Share this post


Link to post
Share on other sites

The UDF converts them into native data-types before returning them :)


A cross-platform implementation of the AutoIt language

My contributions to the AutoIt Community ##AutoIt at freenode, real-time chat

3fHNZJ.gif

Spoiler

If I have hurt or offended you in anyway, Please accept my apologies, I never (regardless of the situation) intend to do that to anybody.

Share this post


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 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://stedolan.github.io/jq/manual/ 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 <<<
       
    • 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://stedolan.github.io/jq/manual/ 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.
    • By argumentum
      #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  
    • By matwachich
      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
    • By Roy_
      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
×
×
  • Create New...