Jump to content

A Non-Strict JSON UDF (JSMN)


Recommended Posts

I think I need another tip.  How about this. How would I get the count of groups in this example:

{   
    "groups": [{
       "id": "11",
       "name": "ItemA"
       },{
       "id": "22",
       "name": "ItemB"
       },{
       "id": "33",
       "name": "ItemC"
    }]
}

This isn't working:

Local $oJson = Json_Decode($Json1)
Local $aoItems = Json_Get($oJson, ".")
ConsoleWrite($aoItems.Count)

 

Edited by NassauSky
Link to post
Share on other sites
  • Replies 287
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Popular Posts

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.

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", "

I wrote a helper function to get specific element in nested array/object returned from Jsmn_Decode() more easily. Here is the code and example: #Include "JSMN.au3" Local $Json = '{"key1" : "value

Posted Images

$ojson   = Json_Decode($JSON)
$aGroups = Json_Get($ojson, ".groups")
ConsoleWrite("Groups count = " & UBound($aGroups) & @CRLF)

.groups is an array of json objects.  So you would get the count of how many array items like you would with any other array.

Edited by TheXman
Link to post
Share on other sites

Correct, the value of .groups is an array, not a JSON object.

You're welcome. :)

Edited by TheXman
Link to post
Share on other sites
  • 1 month later...

Just to inform you about our research results, this library can cause a memory access violation error message that keeps windows from shutting down (stop shutdown and asking the user to hit OK).

Error msg: "The Instruction at 0x%address% referenced memory at 0x%same_address%. The memory could not be written. Click OK to terminate the program.

 
This happened only on certain Win10 machines and even there it was not always reproduceable, happening only e.g. 3 of 5 times.

So again, the error only occured when we used the library in the time window when windows is doing the shutdown, e.g. 
 

OnAutoItExitRegister("__exit_procedure") 

While 1
    Sleep(500)
WEnd

Func __exit_procedure()
    Json_Encode($object)
EndFunc
 

Run this program and then shutdown windows. 

screenshot here http://www.ffastrans.com/frm/forum/viewtopic.php?f=4&t=1184#p6154

 

Edited by emcodem
Link to post
Share on other sites

Thanks for the tipp @Danp2 ..if i am right, the workaround you applied was the same than we did: just don't execute the affected function in the OnAutoItExitRegister callback but somewhen else and grab the json encoded stuff from a global variable instead.

For example we worked around by just using regex on the already encoded json. But a workaround is not a fix and i fear we are not the only ones that suffer from such an issue and spend huge amounts of time to debug it. Thats why i thought its good to post this here.

What i can add additionally, it don't seem to be directly connected to OnAutoItExitRegister. We had the same behaviour in an older version of our program when detecting the program shutdown in our own code and were executing Json_Encode inside an AdlibRegister Function. Using this method, the Adlib function ran thousands of time at runtime without any problem but as it was executed in this time spot when windows shuts down, Json_encode caused the mentioned issue.

Unfortunately, below is not tested but this was about how our old program version worked hehe...

AdlibRegister("_ProcAdmin", 1000)
Func _ProcAdmin()
    ...lots of code
    Json_Encode($object)
    ...lots of code
EndFunc 

 

Edited by emcodem
Link to post
Share on other sites
{
    "type": "success",
    "code": "s-portfolio-0001",
    "description": "Success position",
    "result": {
        "positionList": [
            {
                "AccountID": "ASIA",
                "TradingSymbol": "BANKNIFTY 04FEB2021 CE 34700",
                "ExchangeSegment": "NSEFO",
                "ExchangeInstrumentId": "38544",
                "ProductType": "NRML",
                "Marketlot": "25",
                "Multiplier": "1",
                "BuyAveragePrice": "0.00",
                "SellAveragePrice": "394.89",
                "OpenBuyQuantity": "0",
                "OpenSellQuantity": "200",
                "Quantity": "-200",
                "BuyAmount": "0.00",
                "SellAmount": "78,977.50",
                "NetAmount": "78,977.50",
                "UnrealizedMTM": "34,447.50",
                "RealizedMTM": "0.00",
                "MTM": "34,447.50",
                "BEP": "394.89",
                "SumOfTradedQuantityAndPriceBuy": "0.00",
                "SumOfTradedQuantityAndPriceSell": "78,977.50",
                "MessageCode": 9002,
                "MessageVersion": 1,
                "TokenID": 0,
                "ApplicationType": 0,
                "SequenceNumber": 344181107247201
            },
            {
                "AccountID": "ASIA",
                "TradingSymbol": "BANKNIFTY 04FEB2021 PE 34100",
                "ExchangeSegment": "NSEFO",
                "ExchangeInstrumentId": "46488",
                "ProductType": "NRML",
                "Marketlot": "25",
                "Multiplier": "1",
                "BuyAveragePrice": "0.00",
                "SellAveragePrice": "401.79",
                "OpenBuyQuantity": "0",
                "OpenSellQuantity": "200",
                "Quantity": "-200",
                "BuyAmount": "0.00",
                "SellAmount": "80,358.75",
                "NetAmount": "80,358.75",
                "UnrealizedMTM": "-15,441.25",
                "RealizedMTM": "0.00",
                "MTM": "-15,441.25",
                "BEP": "401.79",
                "SumOfTradedQuantityAndPriceBuy": "0.00",
                "SumOfTradedQuantityAndPriceSell": "80,358.75",
                "MessageCode": 9002,
                "MessageVersion": 1,
                "TokenID": 0,
                "ApplicationType": 0,
                "SequenceNumber": 344181107247202
            },
            {
                "AccountID": "ASIA",
                "TradingSymbol": "BANKNIFTY 04FEB2021 PE 34000",
                "ExchangeSegment": "NSEFO",
                "ExchangeInstrumentId": "46486",
                "ProductType": "NRML",
                "Marketlot": "25",
                "Multiplier": "1",
                "BuyAveragePrice": "0.00",
                "SellAveragePrice": "356.82",
                "OpenBuyQuantity": "0",
                "OpenSellQuantity": "250",
                "Quantity": "-250",
                "BuyAmount": "0.00",
                "SellAmount": "89,203.75",
                "NetAmount": "89,203.75",
                "UnrealizedMTM": "-17,796.25",
                "RealizedMTM": "0.00",
                "MTM": "-17,796.25",
                "BEP": "356.82",
                "SumOfTradedQuantityAndPriceBuy": "0.00",
                "SumOfTradedQuantityAndPriceSell": "89,203.75",
                "MessageCode": 9002,
                "MessageVersion": 1,
                "TokenID": 0,
                "ApplicationType": 0,
                "SequenceNumber": 344181107247203
            },
            {
                "AccountID": "ASIA",
                "TradingSymbol": "BANKNIFTY 04FEB2021 PE 33900",
                "ExchangeSegment": "NSEFO",
                "ExchangeInstrumentId": "36195",
                "ProductType": "NRML",
                "Marketlot": "25",
                "Multiplier": "1",
                "BuyAveragePrice": "0.00",
                "SellAveragePrice": "315.74",
                "OpenBuyQuantity": "0",
                "OpenSellQuantity": "200",
                "Quantity": "-200",
                "BuyAmount": "0.00",
                "SellAmount": "63,147.50",
                "NetAmount": "63,147.50",
                "UnrealizedMTM": "-13,112.50",
                "RealizedMTM": "0.00",
                "MTM": "-13,112.50",
                "BEP": "315.74",
                "SumOfTradedQuantityAndPriceBuy": "0.00",
                "SumOfTradedQuantityAndPriceSell": "63,147.50",
                "MessageCode": 9002,
                "MessageVersion": 1,
                "TokenID": 0,
                "ApplicationType": 0,
                "SequenceNumber": 344181107247204
            },
            {
                "AccountID": "ASIA",
                "TradingSymbol": "BANKNIFTY 04FEB2021 CE 34600",
                "ExchangeSegment": "NSEFO",
                "ExchangeInstrumentId": "38540",
                "ProductType": "NRML",
                "Marketlot": "25",
                "Multiplier": "1",
                "BuyAveragePrice": "0.00",
                "SellAveragePrice": "430.22",
                "OpenBuyQuantity": "0",
                "OpenSellQuantity": "200",
                "Quantity": "-200",
                "BuyAmount": "0.00",
                "SellAmount": "86,043.75",
                "NetAmount": "86,043.75",
                "UnrealizedMTM": "36,433.75",
                "RealizedMTM": "0.00",
                "MTM": "36,433.75",
                "BEP": "430.22",
                "SumOfTradedQuantityAndPriceBuy": "0.00",
                "SumOfTradedQuantityAndPriceSell": "86,043.75",
                "MessageCode": 9002,
                "MessageVersion": 1,
                "TokenID": 0,
                "ApplicationType": 0,
                "SequenceNumber": 344181107247205
            },
            {
                "AccountID": "ASIA",
                "TradingSymbol": "BANKNIFTY 04FEB2021 CE 34500",
                "ExchangeSegment": "NSEFO",
                "ExchangeInstrumentId": "38537",
                "ProductType": "NRML",
                "Marketlot": "25",
                "Multiplier": "1",
                "BuyAveragePrice": "0.00",
                "SellAveragePrice": "469.17",
                "OpenBuyQuantity": "0",
                "OpenSellQuantity": "200",
                "Quantity": "-200",
                "BuyAmount": "0.00",
                "SellAmount": "93,833.75",
                "NetAmount": "93,833.75",
                "UnrealizedMTM": "38,503.75",
                "RealizedMTM": "0.00",
                "MTM": "38,503.75",
                "BEP": "469.17",
                "SumOfTradedQuantityAndPriceBuy": "0.00",
                "SumOfTradedQuantityAndPriceSell": "93,833.75",
                "MessageCode": 9002,
                "MessageVersion": 1,
                "TokenID": 0,
                "ApplicationType": 0,
                "SequenceNumber": 344181107247206
            }
        ]
    }
}

 

 

How can I get result.PositionList into a 2D array.
 

$jsontemp = Json_Decode($oReceived)
    $positionlist = Json_ObjGet($jsontemp, "result.positionList")


 

 

Link to post
Share on other sites
On 2/2/2021 at 1:17 AM, adityaparakh said:

How can I get result.PositionList into a 2D array.
 

$jsontemp = Json_Decode($oReceived)
$positionlist = Json_ObjGet($jsontemp, "result.positionList")

 

@adityaparakh

Since you provided absolutely no information related to what your 2D array should look like or contain, the well-documented example below is very generic.  With 100's of relevant examples across the forums (including many in this topic alone), one would think you could have shown a little more effort than the two lines that you provided. <_<

#include <Constants.au3>
#include <Array.au3>
#include "json.au3" ; <== Modify as needed

Const $JSON_DATA = _
          '{' & _
          '   "type": "success",' & _
          '   "code": "123ABC",' & _
          '   "description": "Another simple example",' & _
          '   "result": {' & _
          '      "fruits": [' & _
          '         {"Fruit": "Apple"     , "Qty": 34700, "Cost": 94.89, "Status": false},' & _
          '         {"Fruit": "Banana"    , "Qty": 34100, "Cost": 01.79, "Status": true} ,' & _
          '         {"Fruit": "Orange"    , "Qty": 34000, "Cost": 56.82, "Status": true} ,' & _
          '         {"Fruit": "Mango"     , "Qty": 33900, "Cost": 15.74, "Status": false},' & _
          '         {"Fruit": "Pineapple" , "Qty": 34600, "Cost": 30.22, "Status": false},' & _
          '         {"Fruit": "Cantaloupe", "Qty": 34500, "Cost": 69.17, "Status": false}'  & _
          '      ]' & _
          '   }' & _
          '}'

json_udf_example()

Func json_udf_example()
    Local $oJson
    Local $aResult[0][3]

    ;Decode JSON to an object
    $oJson  = Json_Decode($JSON_DATA)
    If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", "Unable to decode JSON - @error = " & @error)

    ;For each object in the array
    For $oFruit in json_get($oJson, ".result.fruits")
        ;Add a row of data to the table
        _ArrayAdd($aResult, _
            Json_Get($oFruit, ".Fruit") & "|" & _
            Json_Get($oFruit, ".Qty")   & "|" & _
            Json_Get($oFruit, ".Cost") _
        )
        If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", "_ArrayAdd failed - @error = " & @error)
    Next

    ;Display result
    _ArrayDisplay($aResult, "Example 2D Array", "", 0, Default, "Fruit|Qty|Cost")
EndFunc

image.png.2db70d42fd1f3923eac3e03640febf19.png

Edited by TheXman
Made script more generic
Link to post
Share on other sites
3 hours ago, TheDcoder said:

I am interested in the encoding function as jsmn doesn't provide such a thing.

If you aren't able to find the original source, then at the bottom of this page there are numerous links to github JSON implementations in several different languages.  Or, you can always write your own JSON string encoding routine using RFC 7159 as your reference.

Edited by TheXman
Link to post
Share on other sites

@TheXman Thank you for the links, I am aware of them. I did some research but I realized that I don't really need to depend on jsmn... :)

P.S For anyone who is interested in what I am trying to do, I am basically trying to dump some structs from C into a readable format for debugging purposes, this is for the "EasyCodeIt" project I am working on, see my signature.

EasyCodeIt - A cross-platform AutoIt implementation

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to post
Share on other sites
  • 1 month later...
#include "JSON.au3"
Json_Test()


Func Json_Test()
    Local $sJSON = '[{"name":"Jon", "surname":"Snow"}{"name":"Daenerys","surname":"Targaryen"}]'
    Json_Dump($sJSON)
    Local $oJSON = Json_Decode($sJSON)
    Json_ObjDelete($oJSON, "[0]")
    Local $sJSON2 = Json_Encode($oJSON)
    Json_Dump($sJSON2)
EndFunc

Can someone help me to delete entry

{"name":"Jon", "surname":"Snow"}

?

Link to post
Share on other sites
  • Developers

I think the jason string is invalid and missing a comma :

Local $sJSON = '[{"name":"Jon", "surname":"Snow"},{"name":"Daenerys","surname":"Targaryen"}]'

.. but also believe the UDF has trouble lexing it as it returns an Array in stead of an Object.

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites
  • Developers

mmm that indeed makes sense so one needs to delete the array entry 0 in this case  or just use array entry 1 works too in this example

#include "JSON.au3"
Json_Test()

Func Json_Test()
    Local $sJSON = '[{"name":"Jon", "surname":"Snow"},{"name":"Daenerys","surname":"Targaryen"},]'
    Json_Dump($sJSON)
    Local $oJSON = Json_Decode($sJSON)
    ConsoleWrite(Json_encode($oJSON[1]) & @crlf)
EndFunc

 

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites

If you want to programmatically search the array for the object(s) of interest, instead of hard-coding it, you could do something like:

#include <Constants.au3>
#include <Array.au3>
#Include <json.au3>

Const $JSON_DATA = '[{"name":"Jon","surname":"Snow"},{"name":"Daenerys","surname":"Targaryen"}]'

delete_json_array_items_example()

Func delete_json_array_items_example()
    Local $oJson
    Local $aoJson[0]

    ;Decode JSON
    $aoJson = Json_Decode($JSON_DATA)
    If @error Then Exit MsgBox($MB_ICONERROR + $MB_TOPMOST, "ERROR", "Unable to parse JSON - @error = " & @error)

    ConsoleWrite("Before:" & @CRLF & Json_Encode($aoJson, $JSON_PRETTY_PRINT) & @CRLF)

    ;For each JSON array item
    For $i = UBound($aoJson) - 1 To 0 Step -1
        ;Get object. If it's an object of interest, then remove it from the array
        $oJson = json_get($aoJson, "[" & $i & "]")
        If Json_Get($oJson, ".name") = "Jon" And Json_Get($oJson, ".surname") = "Snow" Then _ArrayDelete($aoJson, $i)
    Next

    ConsoleWrite(@CRLF & "After:" & @CRLF & Json_Encode($aoJson, $JSON_PRETTY_PRINT) & @CRLF)
EndFunc

Console:

Before:
[
    {
        "name": "Jon",
        "surname": "Snow"
    },
    {
        "name": "Daenerys",
        "surname": "Targaryen"
    }
]

After:
[
    {
        "name": "Daenerys",
        "surname": "Targaryen"
    }
]

 

Edited by TheXman
Link to post
Share on other sites
  • Developers
Posted (edited)

.. I do however think there should be some sort of support for deleting array entries in the UDF and we probably could even include it in the objdelete() UDF by testing whether the supplied variable is an Obj or Array....agree? ... so basically combining the existing with your logic.

Jos

Edited by Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to post
Share on other sites

If that question was directed towards me:

Although I would rarely disagree that additional, relevant, functionality is a good thing, adding functionality to a UDF library when that functionality already exists seems a bit unnecessary and duplicative.  JSON arrays are still just arrays.  There's already a very effective UDF that deletes array entries, _ArrayDelete().  What would be the benefit of the json.au3 file having its own  function that basically does the same thing?  Furthermore, how would you implement it in this case where it may have multiple criteria for the selection of an item that needs to be deleted? I mean I know it can be done, but is it really worth the effort when there is already a whole UDF library dedicated to array maintenance and manipulation?

This was just my off-the-cuff opinion.  If I have misunderstood the direction or tenor of your question, please forgive me. 

Edited by TheXman
Link to post
Share on other sites
  • Developers
Posted (edited)

It was just a generic question to all but do appreciate your thoughts. :) 
Looking at the functions we do already have these commands for an Arrray:

  • Json_get()
  • Json_put()

So thought it would be nice to add Json_del() to that list as well. 
Another thought was to add a check at the beginning of eg the Json_*get() functions to check for IsObj() and isArray() and use the "other"function when it is the wrong type of input..... just to make things much easier to use it.   ( just thinking out loud here :) ) 

Jos

Edited by Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

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://github.com/stedolan/jq/wiki jq Online Testing Playground: https://jqplay.org/ jq is a single 32 or 64 bit executable that has no other dependencies.  Just like using the SQLite UDF, the only requirement to use this UDF is that the jq executable reside in a location in which the UDF can execute it.  The latest win32 & win64 versions have been included in the UDF download.  You can always get newer versions from the jq website.
      I don't consider this UDF as a replacement for some of the other JSON UDFs like the one based on JSMN.  If speed and simple JSON parsing are your primary goals, then other UDFs may be a better choice.  However, if you like having the power to do just about anything related to JSON processing/manipulation, using a single UDF, then jq may be worth checking out.  It can be used by novices and experts alike.  Below, is a brief explanation of how jq works, how to use the jq UDF, and a few examples of how to do some simple tasks.  If you want to learn more about jq and what it can do, I would highly suggest checking out the jq website and some of the other resources listed above.
      jq at a high level
      Like 'sed', jq reads JSON in, either through STDIN or one or more files, processes it thru one or more "filters", and outputs the results.  You can, optionally, supply "options" that affect how it reads the input, where it gets its "filters", and how it writes its output.  It looks a little like this:
      JSON ---> jq processor (using supplied filters and options) ---> Output
      So in jq lingo, you basically use "Filters" to tell jq what you want it to do.  So in the UDF file, that is why the main functions ( _jqExec() and _jqExecFile() ) refer to filters and options.  Please make note that jq works with relatively strict JSON.  This means that all JSON read must be conform to the standard.  Luckily, jq is pretty good at identifying where a format error exists in non standard JSON.
      The jq UDF
      There are 2 main funtions in the UDF file, _jqExec and jqExecFile.  With these 2 functions, you can pretty much do anything that jq can do.  The only difference between to two functions is whether the JSON is supplied by a string or a file.  The 2 primary functions simply call the jq executable with the supplied information, after properly formatting the parameters.  There are additional functions in the UDF to easily pretty-print your json, compact-print your json, dump the json data with its associated paths, and see if specific JSON keys exist, but they all just execute the _jqExec or _jqExecFile function with the proper filter.  There are also a couple of extra functions to display what version of the UDF and jq executable you are currently using.  There are also a couple of functions to enable and disable logging of jq information for debugging purposes.  Most of the jq UDF file functions return an @error if unsuccessful.  Some also include @extended info.  Please see the actual function headers for more information on their usage and return values.
      The 2 primary functions below just format your jq request and pass it on the jq executable.  The functions will also properly escape double quotes (") that are used in the filter.  For most simple tasks, you just need to supply the JSON source and a filter.
      _jqExec($sJson, $sFilter, $sOptions = Default, $sWorkingDir = Default) Or _jqExecFile($sJsonFile, $sFilter, $sOptions = Default, $sWorkingDir = Default) Using jq in your script
      As stated earlier, the jq executable must reside somewhere where the script can locate and execute it.  The _jqInit() function always has to be executed before any jq processing occurs.  _jqInit() merely locates the executable or uses the supplied path.  It also clears any previous debug log.  The jq UDF folder contains a jq example script that has several examples to how to do some of the most common JSON processing tasks.  Here are a few examples to get you started:

      How to pretty-print some JSON
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"fruits":[{"Apple":{"color":"Red","season":"Fall"}}, {"Banana":{"color":"Yellow","season":"Summer"}}]}' $sCmdOutput = _jqPrettyPrintJson($sJson) ConsoleWrite(@CRLF & "Pretty-Print JSON" & @CRLF & $sCmdOutput & @CRLF) How to compact-print some JSON
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{ "fruits" : [{"Apple" : {"color":"Red","season":"Fall"}}, {"Banana":{"color":"Yellow","season":"Summer"}}]}' $sCmdOutput = _jqCompactPrintJson($sJson) ConsoleWrite(@CRLF & "Compact-Print JSON" & @CRLF & $sCmdOutput & @CRLF) Dump JSON data (paths and values)
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{ "fruits" : [{"Apple" : {"color":"Red","season":"Fall"}}, {"Banana":{"color":"Yellow","season":"Summer"}}]}' $sCmdOutput = _jqDump($sJson) ConsoleWrite(@CRLF & "Dump JSON paths and values" & @CRLF & $sCmdOutput & @CRLF) How to GET JSON values
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple" : {"color":"Red","season":"Fall"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = '.Banana.color' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("Get color of banana" & @CRLF) ConsoleWrite("Input: : " & _jqCompactPrintJson($sJson) & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF) or
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple" : {"color":"Red","season":"Fall"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = 'getpath(["Banana", "color"])' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("Get color of banana" & @CRLF) ConsoleWrite("Input: : " & _jqCompactPrintJson($sJson) & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF)  
      Check for the existence of a key
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple":{"color":"Red","season":"Fall"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = '.Banana | has("color")' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("Check for existence of color key within Banana object" & @CRLF) ConsoleWrite("Input: : " & _jqCompactPrintJson($sJson) & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF) Count of how many Items in an object
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple":{"color":"Red"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = '.Banana | length' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("How many items in the Banana object" & @CRLF) ConsoleWrite("Input: : " & _jqCompactPrintJson($sJson) & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF) How to PUT/Create/Modify JSON
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sInput = "" $sFilter = 'setpath(["Apple","color"];"Red") | setpath(["Banana","color"];"Yellow") | setpath(["Banana","season"];"Summer")' $sOptions = '-n' ;required if no input supplied $sCmdOutput = _jqExec($sInput, $sFilter, $sOptions) ConsoleWrite("Update/Create JSON" & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & @CRLF & $sCmdOutput & @CRLF) List all of the fruits (top-level keys)
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '{"Apple":{"color":"Red"}, "Banana":{"color":"Yellow","season":"Summer"}}' $sFilter = 'keys | .[]' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("List all top-level keys (fruits)" & @CRLF) ConsoleWrite("Input : " & $sJson & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & @CRLF & $sCmdOutput & @CRLF) Calculate the sum of all of the objects' price * qty
      #include "jq.au3" _jqInit() If @error Then Exit ConsoleWrite("ERROR: Unable to initialize jq - @error = " & @error & @CRLF) $sJson = '[{"id":1,"price":20.00,"qty":10},{"id":2,"price":15.00,"qty":20.25},{"id":3,"price":10.50,"qty":30}]' $sFilter = 'map(.price * .qty) | add' $sCmdOutput = _jqExec($sJson, $sFilter) ConsoleWrite("Calculate the sum of all of the objects' price * qty" & @CRLF) ConsoleWrite("Input : " & $sJson & @CRLF) ConsoleWrite("Filter : " & $sFilter & @CRLF) ConsoleWrite("Output : " & $sCmdOutput & @CRLF)
      The examples above, and the ones in the example files, merely scratch the surface of what jq can do.  It may look intimidating at first but it really isn't that bad once you start playing with it.
      If you have any questions regarding the UDF, or how to perform a certain task using jq, I'll try my best to answer them.  Since jq has been around for a while now, there's also several jq-related questions and answers on StackOverflow.
      If you work with JSON, I hope you find this UDF useful as I do.
      >>> Download in the Files Section <<<
       
    • By TheXman
      This UDF brings the power and flexibility of jq to AutoIt scripts.  jq is an open-source, powerful, and flexible command-line based JSON processor.  As it says on their website, jq is like 'sed' for JSON.  jq can be used for the simplest of tasks like retrieving JSON objects and values (parsing), to very advanced JSON processing using its numerous built-in functions and conditional processing.  Its built-in functions can handle math, selection, conditional processing, mapping, object and array manipulation, flattening, reduction, grouping, and much more.  You can even create your own jq functions.  You can learn more about jq and even play with it in real-time, using jq's online jq playground, all on their website.
      Here and some helpful links to get you more familiar with jq, what can be done with it, its built-in functions, and its syntax.
      jq Website: https://stedolan.github.io/jq/ jq Manual: https://stedolan.github.io/jq/manual/ jqWiki (FAQ, Cookbook, Advanced Topics) https://github.com/stedolan/jq/wiki jq Online Testing Playground: https://jqplay.org/ jq is a single 32 or 64 bit executable that has no other dependencies.  Just like using the SQLite UDF, the only requirement to use this UDF is that the jq executable reside in a location in which the UDF can execute it.  The latest win32 & win64 versions have been included in the UDF download.  You can always get newer versions from the jq website.
      I don't consider this UDF as a replacement for some of the other JSON UDFs like the one based on JSMN.  If speed and simple JSON parsing are your primary goals, then other UDFs may be a better choice.  However, if you like having the power to do just about anything related to JSON processing/manipulation, using a single UDF, then jq may be worth checking out.  It can be used by novices and experts alike.  Below, is a brief explanation of how jq works, how to use the jq UDF, and a few examples of how to do some simple tasks.  If you want to learn more about jq and what it can do, I would highly suggest checking out the jq website and some of the other resources listed above.
      jq at a high level
      Like 'sed', jq reads JSON in, either through STDIN or one or more files, processes it thru one or more "filters", and outputs the results.  You can, optionally, supply "options" that affect how it reads the input, where it gets its "filters", and how it writes its output.  It looks a little like this:
      JSON ---> jq processor (using supplied filters and options) ---> Output
      So in jq lingo, you basically use "Filters" to tell jq what you want it to do.  So in the UDF file, that is why the main functions ( _jqExec() and _jqExecFile() ) refer to filters and options.  Please make note that jq works with relatively strict JSON.  This means that all JSON read must be conform to the standard.  Luckily, jq is pretty good at identifying where a format error exists in non standard JSON.
      The jq UDF
      There are 2 main funtions in the UDF file, _jqExec and jqExecFile.  With these 2 functions, you can pretty much do anything that jq can do.  The only difference between to two functions is whether the JSON is supplied by a string or a file.  The 2 primary functions simply call the jq executable with the supplied information, after properly formatting the parameters.  There are additional functions in the UDF to easily pretty-print your json, compact-print your json, dump the json data with its associated paths, and see if specific JSON keys exist, but they all just execute the _jqExec or _jqExecFile function with the proper filter.  There are also a couple of extra functions to display what version of the UDF and jq executable you are currently using.  There are also a couple of functions to enable and disable logging of jq information for debugging purposes.  Most of the jq UDF file functions return an @error if unsuccessful.  Some also include @extended info.  Please see the actual function headers for more information on their usage and return values.
      The 2 primary functions below just format your jq request and pass it on the jq executable.  The functions will also properly escape double quotes (") that are used in the filter.  For most simple tasks, you just need to supply the JSON source and a filter.
      _jqExec($sJson, $sFilter, $sOptions = Default, $sWorkingDir = Default) Or _jqExecFile($sJsonFile, $sFilter, $sOptions = Default, $sWorkingDir = Default) Using jq in your script
      As stated earlier, the jq executable must reside somewhere where the script can locate and execute it.  The _jqInit() function always has to be executed before any jq processing occurs.  _jqInit() merely locates the executable or uses the supplied path.  It also clears any previous debug log.  The jq UDF folder contains a jq example script that has several examples to how to do some of the most common JSON processing tasks.  Here are a few examples to get you started:

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