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

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                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
TiC01

Thank you so much @TheDcoder, that did the trick :)

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 1

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


Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                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

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                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

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                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

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                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

Visit the SciTE4AutoIt3 Download page for the latest versions  - Beta files                                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

    • 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.
    • jandings
      By jandings
      Hello there,
      since I spent some time to access the REST-API of the web shop system Shopware, I'd like to share a few lines to make life easier for others.
      With this you can access your Shopware database, reading and writing all kind of data. 
      Replies are JSON style.
      To work with JSON I usually depend on either just own AutoIt string operations or this AutoIt library:
      ; File        : Json.au3 (2015.01.08)
      ; Purpose    : A Non-Strict JavaScript Object Notation (JSON) Parser UDF
      ; Author    : Ward
      $UserName="xxxx" ;Shopware credentials of Shopware user who has the API checkbox ticked $PassWord="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ;API-Key of this user, NOT the Password $URL="www.XXX.com/api/" $Command="orders/64682?useNumberAsId=true" ;A list of commands and options is available through shopware REST-API help; Here we read order number 64682 $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "https://" & $URL & $Command , False) $oHTTP.SetCredentials($UserName, $PassWord, 0) $oHTTP.Send() $response = $oHTTP.ResponseText ConsoleWrite ($response & @CRLF & @CRLF)  
    • BJP
      By BJP
      Hello.  I have a program that has used ADO database connection to return a query and then subsequently put the query results into an array using getrows.  See snippet below:
      $constrim="DRIVER={SQL Server};SERVER=xxx-xxxxx\CSC;DATABASE=xxxxxxxxx;uid=xxxxxxxxxx;pwd=xxxxxxxxxxxx;" $adCN = ObjCreate ("ADODB.Connection") ; <== Create SQL connection $adCN.Open ($constrim) ; local $sQuery = "select * from tbl_Apps"                     ; get all applications in the database local $oAppRecordSet = $adCN.Execute($sQuery) local $aAppsInDB = $oAppRecordSet.Getrows(5000) With the code above I can perform array operations very efficiently. 
      Now I need to get this data via JSON which is working (using Ward's JSON UDF)  but the data set returned is large (approx 4MB) and I'm wondering what is the most efficient way to get this data into an array.  
      Dim $obj = ObjCreate ("WinHttp.WinHttpRequest.5.1") $obj.Open("GET", $URL, false) $obj.SetRequestHeader("Content-Type", "application/json") $obj.Send() $json = JSON_decode( $obj.ResponseText ) Any help would be appreciated!!
    • baolo073
      By baolo073
      [ [ [ "Kinh Oanh,\r\n", "Dear Oanh,\r\n", null, null, 3 ], [ "C\u1ea3m \u01a1n b\u1ea1n r\u1ea5t nhi\u1ec1u v졢\u1ee9c th\u01b0 c\u1ee7a b\u1ea1n \u0111\u1ebfn m\u1ed9t v᩠ngṠtr\u01b0\u1edbc. ", "Thank you very much for your letter which arrived a few days ago.", null, null, 3 ], [ "Th\u1eadt \u0111⯧ y뵠khi nghe t\u1eeb b\u1ea1n.\r\n", "It was lovely to hear from you.\r\n", null, null, 3 ], [ "b\u1ea1n \u0111i \u0111㵠v\u1eady.\r\n", "where do you go.\r\n", null, null, 1 ], [ "T\u1ea1m bi\u1ec7t!", "Goodbye!", null, null, 1 ] ], null, "en", null, null, null, 0.91366601, null, [ [ "en" ], null, [ 0.91366601 ], [ "en" ] ] ] How to parse array to json?
×