Jump to content

A Non-Strict JSON UDF (JSMN)


Ward
 Share

Recommended Posts

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)

 

Link to comment
Share on other sites

  • Developers

Added JsonDump() and updated/attached a new Zipfile in first post

 

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 comment
Share on other sites

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

Link to comment
Share on other sites

  • Developers

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 etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

  • 3 weeks later...
  • Developers

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 etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

@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
   }
]

 

Link to comment
Share on other sites

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
Link to comment
Share on other sites

  • Developers
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

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 comment
Share on other sites

  • Developers
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 

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 comment
Share on other sites

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

Link to comment
Share on other sites

  • Developers

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

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 comment
Share on other sites

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.

 

Link to comment
Share on other sites

  • Developers

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 etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

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
Link to comment
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
 Share

×
×
  • Create New...