Jump to content
Ward

A Non-Strict JSON UDF (JSMN)

Recommended Posts

Danp2

Actually, that's retrieving the key when I really it's value. Here's my latest rendition --

Local $sJSON = '{"value":{"element-6066-11e4-a52e-4f735466cecf":"638265bf-bd34-4ea4-8605-b719c9c98538"}}'
Local $Obj = Json_Decode($sJSON)
Local $Obj2 = Json_Get($Obj, "[value]")
Local $sKey = Json_ObjGetKeys($Obj2)[0]
Local $sResult = Json_Get($Obj, "[value][" & $sKey & "]")
ConsoleWrite($sResult & @CRLF)

 

Share this post


Link to post
Share on other sites
TiC01

Hi all,

 

I'm also having a problem with JSON. I'm trying to convert a HUGH autoit array to a JSON file, but there's just one thing I can't get done and that's creating an EMPTY array in JSON

 

example:

{
    "Author": [
        {
            "A": [
                {
                    "Book": "Away from here",
                    "ISBN": "Think-of-something"
                },
                {
                    "Book": "Help required",
                    "ISBN": "again a pattern"
                }
            ]
        },
        {
            "B": [
            ]
        },
        {
            "C": [
                {
                    "Book": "B is the problem",
                    "ISBN": "blablabla"
                }
            ]
        }
    ]
}

 

So, how can I get "B" created how it is now... All I can get done is something like:

{
            "B": [
==>>>>          ""
            ]
        }

And I don't want these ""  .....

 

Please advise and thanks in advance

Share this post


Link to post
Share on other sites
Jos

Show an script that you are testing with so we can see what you are doing.

10 minutes ago, TiC01 said:

And I don't want these ""  .....

Don't know what you mean by that comment.

Jos

Edited by Jos

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

Share this post


Link to post
Share on other sites
TiC01

I want to create

{
            "B": [
            ]
        },

instead of

{
            "B": [
==>>>>          ""
            ]
        },

 

I've tried :

Json_Put($JSONObj,'["Books"]['& $zz & ']["' & $a_BookListAll[$zz][0] & '"][0]',"" )  ... this didn't work

Json_Put($JSONObj,'["Books"]['& $zz & ']["' & $a_BookListAll[$zz][0] & '"][0]',"[]" )  .. this didnt't work either

 

Also tried:

            Local $array[1] = []
            Json_Put($JSONObj,'["Books"]['& $zz & ']["' & $a_BookListAll[$zz][0] & '"]', $array)

 

and

            Local $array[1] = []
            Json_Put($JSONObj,'["F"]['& $zz & ']["' & $a_BookListAll[$zz][0] & '"][0]', $array)

 

Just can't get the result as in the first codebox

 

$zz is a counter btw, and $a_BookListAll is a 2 dimensional array...

 

Part of script:

Func _CreateJSON()

    Local $JSONObj

    For $zz = 0 to UBound($a_BookListAll)-1

        If UBound($a_BookListAll[$zz][4]) == 0 Then
            Local $array[1] = []
            Json_Put($JSONObj,'["Author"]['& $zz & ']["' & $a_BookListAll[$zz][0] & '"]', $array)
        EndIf


        For $xx = 0 to UBound($a_BookListAll[$zz][4])-1
            $InnerArray = $a_BookListAll[$zz][4]
;           ConsoleWrite(@TAB & "Processing book [" & $xx+1 & "/" & UBound($InnerArray) & "]: " & $InnerArray[$xx][2] & @CRLF)

            Json_Put($JSONObj,'["Author"]['& $zz & ']["' & $a_BookListAll[$zz][0] & '"]['& $xx & ']["Book"]', $InnerArray[$xx][2])
            Json_Put($JSONObj,'["Author"]['& $zz & ']["' & $a_BookListAll[$zz][0] & '"]['& $xx & ']["ISBN"]', $InnerArray[$xx][3])
            Json_Put($JSONObj,'["Author"]['& $zz & ']["' & $a_BookListAll[$zz][0] & '"]['& $xx & ']["Shop"]', $InnerArray[$xx][4])
        Next
    Next

    $iTimer = TimerInit()
    ConsoleWrite(JSon_Encode($JSONObj, $Json_PRETTY_PRINT) & @CRLF)
    ConsoleWrite(TimerDiff($iTimer) & @CRLF)
EndFunc

 

Edited by TiC01

Share this post


Link to post
Share on other sites
TheDcoder
21 minutes ago, TiC01 said:

            Local $array[1] = []

Make that:

Local $aArray[0]

 


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

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

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites
TheDcoder

No problem, $aArray[0] creates an empty array, you were using $aArray[1] which was creating an array with a single element/row, by default all variables are strings so that one element translated into an empty string, this is why you were seeing a single "" in the outputted JSON :D

Edited by TheDcoder
  • Like 2

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

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

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites
TiC01

Maybe another stupid question ... Is it possible to implement a progress indicator while encoding/decoding a json string. My json is getting kind of big right now (approx 7MB) and it takes at least 45 seconds to decode.. would be nice to see how far it is while waiting.

Share this post


Link to post
Share on other sites
x_bennY

How do i get the object count? When i try to do it i receive this error:

 

: ==> Variable must be of type "Object".:
Return $Object.Count
Return $Object^ ERROR

 

$data = fileread("test.json")
$object = json_decode($data)

 

Edited by x_bennY

Share this post


Link to post
Share on other sites
Jos

You aren't providing the "test.json" input file, so can only guess that the json_decode($data) doesn't return an object but rather an @error, for which you aren't checking.

Jos


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

Share this post


Link to post
Share on other sites
x_bennY

@Jos

Hey, sorry, i forgot to post it!

[
   {
      "IDPredio":9,
      "DSPredio":"Anfi Teatro",
      "DSLocalizacao":"No prédio de direito",
      "DSCursos":"Vários",
      "NOImagem":"anfiteatro.jpg",
      "NRSalasPredio":null
   },
   {
      "IDPredio":16,
      "DSPredio":"Business Andar Superior",
      "DSLocalizacao":"Shopping Boulevard",
      "DSCursos":"Varios",
      "NOImagem":"boulevard.jpg",
      "NRSalasPredio":7
   },
   {
      "IDPredio":13,
      "DSPredio":"Business Terreo",
      "DSLocalizacao":"Shopping Boulevard",
      "DSCursos":"Varios",
      "NOImagem":"boulevard_terreo.jpg",
      "NRSalasPredio":8
   },
   {
      "IDPredio":8,
      "DSPredio":"Cine Teatro",
      "DSLocalizacao":"Próximo ao prédio tecnológico",
      "DSCursos":"Vários",
      "NOImagem":"cineteatro.jpg",
      "NRSalasPredio":null
   },
   {
      "IDPredio":5,
      "DSPredio":"Prédio Biomédicas",
      "DSLocalizacao":"Próximo ao Centro de Vivências",
      "DSCursos":"Vários",
      "NOImagem":"biomedicas.jpg",
      "NRSalasPredio":41
   },
   {
      "IDPredio":4,
      "DSPredio":"Prédio Humanas",
      "DSLocalizacao":"Próximo a entrada principal",
      "DSCursos":"Direito, Artes Cênicas",
      "NOImagem":"humanas.jpg",
      "NRSalasPredio":32
   },
   {
      "IDPredio":6,
      "DSPredio":"Prédio Inotec",
      "DSLocalizacao":"Próximo a biblioteca",
      "DSCursos":"Vários",
      "NOImagem":"inotec.jpg",
      "NRSalasPredio":23
   },
   {
      "IDPredio":2,
      "DSPredio":"Prédio Tecnológico",
      "DSLocalizacao":"Próximo ao Cineteatro",
      "DSCursos":"Ciência da Computação, Sistemas de Informação",
      "NOImagem":"tecnologico.jpg",
      "NRSalasPredio":36
   },
   {
      "IDPredio":17,
      "DSPredio":"Sequenciais",
      "DSLocalizacao":"Mesmo predio da biblioteca",
      "DSCursos":"vários",
      "NOImagem":"inotec.jpg",
      "NRSalasPredio":6
   }
]

 

Share this post


Link to post
Share on other sites
hmobron

Hello thanks for the great UDF.

Can you please explain how to access non root values? Root value like .firstname  = Willem Cornelis i can access by using Json_ObjGet( $json2, "firstname")

From Json_Dump

 .families[0].spouse.lastname  = Engel 

 .mother.sosa  =2

I running Autoit script 3.3.14.3 with Json(2018.01.13).zip

note json.au3 in the head says ; File        : Json.au3 (2015.01.08)

Edited by hmobron

Share this post


Link to post
Share on other sites
Jos
14 hours ago, x_bennY said:

sorry, i forgot to post it!

Thanks, that helps. So the returned information is not an object so that is why you get that error.
What are you exactly after in terms of a count for this json data?

Jos

  • Like 1

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

Share this post


Link to post
Share on other sites
Jos
4 hours ago, hmobron said:

Hello thanks for the great UDF.

Can you please explain how to access non root values? Root value like .firstname  = Willem Cornelis i can access by using Json_ObjGet( $json2, "firstname")

From Json_Dump

 .families[0].spouse.lastname  = Engel 

 .mother.sosa  =2

I running Autoit script 3.3.14.3 with Json(2018.01.13).zip

note json.au3 in the head says ; File        : Json.au3 (2015.01.08)

I don't understand the question as the json_dump UDF I wrote should tell you exactly what the keys is for a specific field.
It helps when you post some example code, define what you expect and what is going wrong.

Jos 

  • Like 1

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

Share this post


Link to post
Share on other sites
x_bennY
1 hour ago, Jos said:

Thanks, that helps. So the returned information is not an object so that is why you get that error.
What are you exactly after in terms of a count for this json data?

Jos

I just want to know how many sections that json have... in that case it has 9

Share this post


Link to post
Share on other sites
Jos

You could use this logic and turn that into a Func:

#include <json.au3>
Global $data = FileRead("test.json")
Global $object = json_decode($data) 
Global $i = 0
While 1
    $product_id = json_get($object, '[' & $i & ']')
    If @error Then ExitLoop
    $i += 1
WEnd
ConsoleWrite('Number of records:' & $i & @CRLF)

Jos

Edited by Jos
Cut&Paste error
  • Like 1

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

Share this post


Link to post
Share on other sites
hmobron
4 hours ago, Jos said:

I don't understand the question as the json_dump UDF I wrote should tell you exactly what the keys is for a specific field.
It helps when you post some example code, define what you expect and what is going wrong.

Jos 

O there is nothing wrong with the code. I am wrong :)

I don't understand how to get the values from the keys. This from the dump   .mother.sosa  =2 .

 Json_ObjGet( $json2, 'mother=>sosa')  = ''

 Json_ObjGet( $json2, "['mother']['sosa']") = ''

 Json_ObjGet( $json2, ".mother.sosa") = ''

 Json_ObjGet( $json2, "\mother\sosa") = '' and so on.

 

Share this post


Link to post
Share on other sites
Jos

As simple as:  Json_ObjGet( $json2, ".mother.sosa")... but again...  post a code snippet with the test data so I can see what is happening.

Jos

Edited by Jos

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

Share this post


Link to post
Share on other sites
hmobron
8 hours ago, Jos said:

As simple as:  Json_ObjGet( $json2, ".mother.sosa")... but again...  post a code snippet with the test data so I can see what is happening.

Jos

Sorry, tested that to.

Local $hFileOpen = FileOpen('json.txt')
Local $sFileRead = FileRead($hFileOpen)
FileClose($hFileOpen)


$json2 = Json_Decode($sFileRead)
if @error then MsgBox(0,'',@error)

ConsoleWrite('output1: ' & Json_ObjGet( $json2, '.mother.sosa') &  @LF )
ConsoleWrite('output: ' & Json_ObjGet( $json2, "lastname") &  @LF )

Json_Dump($sFileRead)

At the console:

output1: 
output: Mobron

The json file is large, so i uploaded to my domain: https://mobron.nl/wp-content/uploads/2018/02/json.txt

It is a output from a web api.

Edited by hmobron

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

  • Similar Content

    • TheXman
      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, 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 a replacement for some of the other JSON UDFs like the one based on JSMN.  If speed and simple JSON parsing are you 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) The examples above, and the ones in the example file, 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 suggestions on how to make the UDF better, or find a bug, please let me know.  I only started using it about a week ago.  Nevertheless, 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.
       
      Download:
      jq_udf_v1.1.0.zip
       
       
    • Skysnake
      By Skysnake
      I know how JSON works. However JSON data is typically received from web based servers. 
       
      My question is:
      Has anyone considered to use, or currently actively using JSON as an internal data container? 
      Internal here as in an ordinary AutoIt data type, generated, populated and manipulated within an AutoIt script, without any external data sources. 
      The JSON and BinaryCall UDFs work well and appear the de facto defaults. Are there any thoughts on using JSON for internal variable values instead of the typical array? 
      Also, there can be situations where such a JSON collection contains an array and it will have to be parsed using typical array functions. 
      Currently I am working on a small project where I have to keep and use various identifiers from different sources. There are several ideas in this regard, some involving SQL child tables and arrays stored with keys (maps), which lead me to think that JSON may be a more suitable data container. It readily shrinks and stretches, allowing for dynamic data growth.  JSONs ability to add new repeating data groups on the fly makes it particularly powerful and appealing. 
      Ideas and suggestions welcome
      Skysnake
    • jantograaf
      By jantograaf
      Hi all,
      I'm trying to create a script that runs a JSON-query and then can retrieve some variables out of the returned, decoded object using JSON.au3. I have tried some other examples on this forum, but I'm stuck at one point. My query works perfectly and gets loaded into the variable $data. Then, decoding $data to $object seems to work as well. But then I can't get the date-field out of this JSON-structure with my script.
      The JSON-structure returned looks like this:
      { "content": [ { "id": "451ec583-8f27-4926-82a3-a2d85e57a110", "createdDate": "2018-08-08T08:40:57.449004Z", "updatedDate": "2018-08-08T08:40:57.449004Z", "lastOpenedDate": "2018-08-08T08:40:57.449004Z", "date": "2018-04-26T00:00:00", "description": "X-Ray Exam", "patient": { "id": "f857238a-c75d-4760-b8d1-8f50f8f9bbfa", "createdDate": "2018-08-08T08:40:37.623976Z", "updatedDate": "2018-08-08T08:40:37.623976Z", "lastOpenedDate": "2018-08-08T08:40:37.623976Z", "name": "Fuerstonia", "birthDate": "2014-06-08", "breed": "", "chip": "", "color": "", "damsire": "", "sire": "", "neutered": false, "orthancUuid": "", "sex": "U", "species": "Paard", "ueln": "De 431310762114", "pmsReference": "", "origin": "" }, "type": "study", "accessionNumber": "KME201806960467", "instanceUid": null, "orthancUuid": "", "sent": false, "seriesCount": 0, "modalityType": "RX", "typeAndModality": "study RX", "client": { "id": "be627195-8458-4927-8446-f1ef37b917a4", "createdDate": "2018-08-08T08:40:31.433968Z", "updatedDate": "2018-08-08T08:40:31.433968Z", "lastOpenedDate": "2018-08-08T09:26:49.512298Z", "via": "", "extraInfo": "", "pmsReference": "", "contact": { "id": "406cc555-c491-4c29-b6bb-8d903f0e35a9", "createdDate": "2018-08-08T08:40:31.428968Z", "updatedDate": "2018-08-08T08:40:31.428968Z", "lastName": "Client 1", "firstName": "", "company": "", "email": "", "language": "nl", "phone": "", "address": { "id": "6fc7703c-137a-4e0a-ba96-8c7f38f2044b", "city": "", "country": "", "line": "", "postalCode": "" } } } }, My script looks like this:
      #RequireAdmin #include <json.au3> #include <inet.au3> #include <File.au3> ;Create a handle to a logfile (will be created if it doesnt exist) Global $logfile = FileOpen("C:\VSOL\VSTK\Logs\MigrationFix\MigrationFix.log",9) FileWriteLine($logfile,"Start script") ;Create the URL with the JSON-query $URL = "http://localhost:8080/v0/studies/?seriesCount=1" ;Catch the query output into a variable $data = _INetGetSource($URL) ;Check if there is any data at all in this variable, if not, exit If Not $data Then MsgBox(1,"Error","No answer. Server is probably not running.") Exit EndIf ;For debugging purposes FileWriteLine($logfile,$data) ;Decode the JSON_string into a useable object $object = Json_Decode($data,1000) If @error Then FileWriteLine($logfile,"Error decoding JSON") Exit EndIf Local $i = 0 ;Start a loop to retrieve the study date of each study... While 1 $study_date = json_get($object,'[' & $i & '].date') If @error Then FileWriteLine($logfile,"Study-Date retrieval error") ExitLoop EndIf $i = $i + 1 WEnd ;Close the logfile FileWriteLine($logfile,"Stop script") FileClose($logfile) ;Open the logfile for quick reference ShellExecute("C:\VSOL\VSTK\Logs\MigrationFix\MigrationFix.log") If believe it has something to do with my json_get($object...)-command. Anyone who can point me in the right direction?
      Thanks in advance!
      Kind regards
    • jesus40
      By jesus40
      Hello friends, I need help getting data from json. I read json from url into a variable.
      Is possible to get volume_USD value etc.  where product_id= "ETH-BTC", ? So I want get "37421.69109185" as variable.
      I think is better keeping it in the memory as variable. Or easier to convert it to db or csv?
       
       
      #include <Inet.au3> #include <json.au3> $URL="https://api.abucoins.com/products/stats" $data = _INetGetSource($URL) MsgBox("","",$data) $object=json_decode($data) local $i=0 while 1 $message=json_get($object,'[product_id]');???????????????????????????????? MsgBox("","volume_USD",$message) $i=$i+1 WEnd  
      the json structure is here:
      https://api.abucoins.com/products/stats
      [ { "product_id": "ETH-BTC", "last": "0.05202015", "open": "0.05009375", "high": "0.05250000", "low": "0.04872420", "volume": "47.77440456", "volume_BTC": 2.48523169, "volume_USD": 37421.69109185, "volume_7d": "364.40240341", "volume_30d": "3555.83377072", "change": "3.85" }, { "product_id": "LTC-BTC", "last": "0.01737490", "open": "0.01744636", "high": "0.01779000", "low": "0.01658091", "volume": "67.62762830", "volume_BTC": 1.17502328, "volume_USD": 17941.95920676, "volume_7d": "611.57893068", "volume_30d": "3881.57766044", "change": "-0.41" }, { "product_id": "ETC-BTC", "last": "0.00191846", "open": "0.00189001", "high": "0.00198000", "low": "0.00162741", "volume": "66.48327742", "volume_BTC": 0.12754551, "volume_USD": 1947.54976323, "volume_7d": "738.94495089", "volume_30d": "4090.74712156", "change": "1.51" }, { "product_id": "ZEC-BTC", "last": "0.03466163", "open": "0.03365452", "high": "0.03466163", "low": "0.03295811", "volume": "33.40101560", "volume_BTC": 1.15773364, "volume_USD": 17677.95599574, "volume_7d": "191.15953471", "volume_30d": "887.70158297", "change": "2.99" } ]  
       
    • satanico64
      By satanico64
      hi guys !
      how are you ? fine ? yeahhh
      Here is my problem:
      I have 2 autoit applications, a.exe and b.exe
      In a.exe, i call b.exe with a json as parameter:
      FileWrite("N:\+++ Dev\ClientServeur\FolderMonitor.nca", "lejson in A:" & Json_Encode($json_tmp)& @CRLF) Run(@ScriptDir & "\FolderMonitor.exe " & Json_Encode($json_tmp) )                        
              In program B:
      ;Firstline of program: FileWrite("N:\+++ Dev\ClientServeur\FolderMonitor.nca", @CRLF & "json in B:" & $CmdLine[1] & @CRLF)        
              Output:
                     
              lejson in A:{"DOSSIERS":{"Dossier_Hidden":"N:\\+++ Dev\\ClientServeur\\","Dossier_du_script":"N:\\+++ Dev\\ClientServeur\\","Fichier_Historique":"N:\\+++ Dev\\ClientServeur\\Historique.log","Fichier_DEBUG":"N:\\+++ Dev\\ClientServeur\\FolderMonitor.nca"}}
              json in B  :{DOSSIERS:{Dossier_Hidden:N:\\+++ Dev\\ClientServeur\\,Dossier_du_script:N:\\+++ Dev\\ClientServeur\\,Fichier_Historique:N:\\+++ Dev\\ClientServeur\\Historique.log,Fichier_DEBUG:N:\\+++ Dev\\ClientServeur\\FolderMonitor.nca}}
      As you see, i lost my quote in my json so it's au problem to parse my json.
      I use THIS library
      I tried different type of encoding (ex JSON_STRICT_PRINT), but i don't think that it's the problem. Maybe i'm wrong
       
      thanks
      Nicolas.
×