Jump to content

A Non-Strict JSON UDF (JSMN)


Ward
 Share

Recommended Posts

3 minutes ago, Jos said:

Initial topic post link not working?

This works: https://www.autoitscript.com/forum/applications/core/interface/file/attachment.php?id=69571

I have found it after re-reading the whole post word by word.

This link seems very similar (right above my post): https://www.autoitscript.com/forum/applications/core/interface/file/attachment.php?id=72547

Should I pick one or does it not matter (in terms of future compatibility)?

Link to comment
Share on other sites

  • Developers
23 minutes ago, antai said:

Should I pick one or does it not matter (in terms of future compatibility)?

No idea what you mean with these comments, but it is pretty strait forward: Use the one that is posted in the initial post and you have the latest version I've uploaded. All other links are what they are: other links. ;) 

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

On 3/24/2013 at 12:23 PM, whizter said:

I get an empty array with ~500 elements when I get into the asks or bids arrays.

 

Func getArrayFromJson($URI,$reqAuth,$post="")
$result = Jsmn_Decode(goxRequest($URI,_Iif($reqAuth>0,getNonce()&$post,"")))
$result = Jsmn_ObjTo2DArray($result)
If (Not IsArray($result) Or UBound($result) = 0) Then
MsgBox(0,"Error: "&$URI,$result)
Return 0
Else
If(NOT IsArray($result[2][1])) Then
MsgBox(0,$URI,$result[2][1])
Return 0
EndIf
Return $result[2][1]
EndIf
EndFunc

 

Can I read the whole json into an array?

Some easy way like the example above - the $result should be an array containing all the elements.

The Json_Decode function does not exist tough.

Is this UDF good for this task, or is Stringsplit better suited for this task?

Link to comment
Share on other sites

  • Developers
1 hour ago, antai said:

(can I delete / edit my old posts to avoid this spam)?

Soon you will when you are move out of the "New Members" group.

1 hour ago, antai said:

Json_ObjTo2DArray does not exists so it does not work anyway.

Guess this is a statement about a conclusion you made for a challenge you have, rather than a question.... Maybe share that challenge as a question? ;) 

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

9 hours ago, Jos said:

 

Guess this is a statement about a conclusion you made for a challenge you have, rather than a question.... Maybe share that challenge as a question? ;) 

The challenge is to read a json file (basically excell table but in json) into a 2D array. Is it possible with this UDF?

There is this function at the first page of this thread:

Func getArrayFromJson($URI,$reqAuth,$post="")
    $result = Jsmn_Decode(goxRequest($URI,_Iif($reqAuth>0,getNonce()&$post,"")))
    $result = Jsmn_ObjTo2DArray($result)
    If (Not IsArray($result) Or UBound($result) = 0) Then
        MsgBox(0,"Error: "&$URI,$result)
        Return 0
    Else
        If(NOT IsArray($result[2][1])) Then
            MsgBox(0,$URI,$result[2][1])
            Return 0
        EndIf
    Return $result[2][1]
    EndIf
EndFunc

The code does not work for few errors, most notably that Json_ObjTo2DArray() is an undefined function.

Is the function custom made or is it somwhere hidden in the jsonau3?

Link to comment
Share on other sites

  • 2 weeks later...

I've searched throughout this forum and the net for an easy way to extract JSON data from an existing file.  Changing the source file data format is not an option, but I managed to extract JSON data.  Using the extracted string as a test, I have been unsuccessful in retrieving data values.  I've tried different variations of the function-calling syntax, but have been unsuccessful. What am I doing wrong? 

Here is one of my attempts using the UDF posted by TheXman on 2021/11/20:

#include <Json.au3>
Local $TestString = 'headerName:"Item Title", field:"ItemTitle", sortable:true, width:259, checkboxSelection:true, headerCheckboxSelection:true'
Local $Obj = Json_Decode('{JsonItem:[{' & $TestString & '}]}')
Local $TestResult = Json_Get($Obj, '[JsonItem][headerName]')
 msgbox(0,"Test", "$TestResult = " & $TestResult)

Edited by BrunoJ
Link to comment
Share on other sites

1 hour ago, BrunoJ said:

I've searched throughout this forum and the net for an easy way to extract JSON data from an existing file.  Changing the source file data format is not an option, but I managed to extract JSON data.  Using the extracted string as a test, I have been unsuccessful in retrieving data values.  I've tried different variations of the function-calling syntax, but have been unsuccessful. What am I doing wrong? 

Here is one of my attempts using the UDF posted by TheXman on 2021/11/20:

#include <Json.au3>
Local $TestString = 'headerName:"Item Title", field:"ItemTitle", sortable:true, width:259, checkboxSelection:true, headerCheckboxSelection:true'
Local $Obj = Json_Decode('{JsonItem:[{' & $TestString & '}]}')
Local $TestResult = Json_Get($Obj, '[JsonItem][headerName]')
 msgbox(0,"Test", "$TestResult = " & $TestResult)

I've solved it by looking at more postings by people looking for help.  I can use dot notation to retrieve the values.  This works:

#include <Json.au3>

Local $TestString = 'headerName:"Item Title", field:"ItemTitle", sortable:true, width:259, checkboxSelection:true, headerCheckboxSelection:true'
local $Obj = Json_Decode('{' & $TestString & '}')
Local $TestResult = Json_Get($Obj, '.headerName')
 msgbox(0,"Test", "$TestResult = " & $TestResult)

Link to comment
Share on other sites

  • 2 weeks later...

hi

i have been having a heck of a time trying to get the displayName from this json file.  the multi layer of the JSON is what i think is tricky - success?, result, participants (dont think success is a layer but have tried with and without it also.  since i am only trying to get all displayName entries, maybe stringregexp is better suited?  havent gotten that working either

Local $aArray = StringRegExp($sFileContents, '"displayName": [A-Za-z]', 3)
_ArrayDisplay($aArray)

any help would be GREATLY appreciated!

json snippet

Quote

{
  "success": true,
  "result": {
    "participants": [
      {
        "id": "00d0ab00-00e0-0000-acfc-0d00d00b000b",
        "emailAddress": "Bob.Smith@xyz.com",
        "displayName": "Bob Smith (BS)",
        "firstName": "Bob",
        "lastName": "Smith"
      },
      {
        "id": "000ca000-0d0a-0000-00d0-0e0a0f000000",
        "emailAddress": "Jane.Jones@xyz.com",
        "displayName": "Jane Jones (JJ)",
        "firstName": "Jane",
        "lastName": "Jones"
      },

 

#include "JSON.au3"

$json = @ScriptDir & "\response_1674826797651.json"

Local $sFileContents = FileRead($json)
Local $oJson = Json_Decode($sFileContents)

For $x = 0 To UBound($oJson) - 1
    $sDisplayName = Json_Get($oJson, '["result.participants"][' & $x & ']["displayName"]')

    ConsoleWrite($sDisplayName & @CRLF)
Next

 

Link to comment
Share on other sites

The Json_Dump function can be used to assist with this type of issue. Here's an example --

#include "JSON.au3"

$json = '{' & _
'  "success": true,' & _
'  "result": {' & _
'    "participants": [' & _
'      {' & _
'        "id": "00d0ab00-00e0-0000-acfc-0d00d00b000b",' & _
'        "emailAddress": "Bob.Smith@xyz.com",' & _
'        "displayName": "Bob Smith (BS)",' & _
'        "firstName": "Bob",' & _
'        "lastName": "Smith"' & _
'      },' & _
'      {' & _
'        "id": "000ca000-0d0a-0000-00d0-0e0a0f000000",' & _
'        "emailAddress": "Jane.Jones@xyz.com",' & _
'        "displayName": "Jane Jones (JJ)",' & _
'        "firstName": "Jane",' & _
'        "lastName": "Jones"' & _
'      }' & _
'   ]' & _
'  }' & _
'}'

Json_Dump($json)

And the resulting output --

   +-> .success  =True
    +-> .result.participants[0].id  =00d0ab00-00e0-0000-acfc-0d00d00b000b
    +-> .result.participants[0].emailAddress  =Bob.Smith@xyz.com
    +-> .result.participants[0].displayName  =Bob Smith (BS)
    +-> .result.participants[0].firstName  =Bob
    +-> .result.participants[0].lastName  =Smith
    +-> .result.participants[1].id  =000ca000-0d0a-0000-00d0-0e0a0f000000
    +-> .result.participants[1].emailAddress  =Jane.Jones@xyz.com
    +-> .result.participants[1].displayName  =Jane Jones (JJ)
    +-> .result.participants[1].firstName  =Jane
    +-> .result.participants[1].lastName  =Jones

Using the above details, I would change your Json_Get line to this --

$sDisplayName = Json_Get($oJson, '.result.participants[' & $x & '].displayName')

 

Link to comment
Share on other sites

2 hours ago, Danp2 said:

The Json_Dump function can be used to assist with this type of issue. Here's an example --

#include "JSON.au3"

$json = '{' & _
'  "success": true,' & _
'  "result": {' & _
'    "participants": [' & _
'      {' & _
'        "id": "00d0ab00-00e0-0000-acfc-0d00d00b000b",' & _
'        "emailAddress": "Bob.Smith@xyz.com",' & _
'        "displayName": "Bob Smith (BS)",' & _
'        "firstName": "Bob",' & _
'        "lastName": "Smith"' & _
'      },' & _
'      {' & _
'        "id": "000ca000-0d0a-0000-00d0-0e0a0f000000",' & _
'        "emailAddress": "Jane.Jones@xyz.com",' & _
'        "displayName": "Jane Jones (JJ)",' & _
'        "firstName": "Jane",' & _
'        "lastName": "Jones"' & _
'      }' & _
'   ]' & _
'  }' & _
'}'

Json_Dump($json)

And the resulting output --

   +-> .success  =True
    +-> .result.participants[0].id  =00d0ab00-00e0-0000-acfc-0d00d00b000b
    +-> .result.participants[0].emailAddress  =Bob.Smith@xyz.com
    +-> .result.participants[0].displayName  =Bob Smith (BS)
    +-> .result.participants[0].firstName  =Bob
    +-> .result.participants[0].lastName  =Smith
    +-> .result.participants[1].id  =000ca000-0d0a-0000-00d0-0e0a0f000000
    +-> .result.participants[1].emailAddress  =Jane.Jones@xyz.com
    +-> .result.participants[1].displayName  =Jane Jones (JJ)
    +-> .result.participants[1].firstName  =Jane
    +-> .result.participants[1].lastName  =Jones

Using the above details, I would change your Json_Get line to this --

$sDisplayName = Json_Get($oJson, '.result.participants[' & $x & '].displayName')

 

thank you for your help!

i think i may be misunderstanding you.... because i am not getting the values for displayName 

#include "JSON.au3"

$json = '{' & _
'  "success": true,' & _
'  "result": {' & _
'    "participants": [' & _
'      {' & _
'        "id": "00d0ab00-00e0-0000-acfc-0d00d00b000b",' & _
'        "emailAddress": "Bob.Smith@xyz.com",' & _
'        "displayName": "Bob Smith (BS)",' & _
'        "firstName": "Bob",' & _
'        "lastName": "Smith"' & _
'      },' & _
'      {' & _
'        "id": "000ca000-0d0a-0000-00d0-0e0a0f000000",' & _
'        "emailAddress": "Jane.Jones@xyz.com",' & _
'        "displayName": "Jane Jones (JJ)",' & _
'        "firstName": "Jane",' & _
'        "lastName": "Jones"' & _
'      }' & _
'   ]' & _
'  }' & _
'}'

$json = Json_Dump($json)


For $x = 0 To UBound($json) - 1
    $sDisplayName = Json_Get($json, '.result.participants[' & $x & '].displayName')

    ConsoleWrite($sDisplayName & @CRLF) 
Next

 

Link to comment
Share on other sites

Yes, you misunderstood. The Json_Dump usage is how you can determine the proper keys to retrieve the data, but you don't need it in the final script. Here's one way that you could do it --

#include "JSON.au3"

$json = '{' & _
'  "success": true,' & _
'  "result": {' & _
'    "participants": [' & _
'      {' & _
'        "id": "00d0ab00-00e0-0000-acfc-0d00d00b000b",' & _
'        "emailAddress": "Bob.Smith@xyz.com",' & _
'        "displayName": "Bob Smith (BS)",' & _
'        "firstName": "Bob",' & _
'        "lastName": "Smith"' & _
'      },' & _
'      {' & _
'        "id": "000ca000-0d0a-0000-00d0-0e0a0f000000",' & _
'        "emailAddress": "Jane.Jones@xyz.com",' & _
'        "displayName": "Jane Jones (JJ)",' & _
'        "firstName": "Jane",' & _
'        "lastName": "Jones"' & _
'      }' & _
'   ]' & _
'  }' & _
'}'

Local $oJson = Json_Decode($json)
Local $x = 0

While 1
    $sDisplayName = Json_Get($oJson, '.result.participants[' & $x & '].displayName')
    If @error Then ExitLoop

    ConsoleWrite($sDisplayName & @CRLF)
    $x += 1
WEnd

 

Link to comment
Share on other sites

31 minutes ago, Danp2 said:

Yes, you misunderstood. The Json_Dump usage is how you can determine the proper keys to retrieve the data, but you don't need it in the final script. Here's one way that you could do it --

#include "JSON.au3"

$json = '{' & _
'  "success": true,' & _
'  "result": {' & _
'    "participants": [' & _
'      {' & _
'        "id": "00d0ab00-00e0-0000-acfc-0d00d00b000b",' & _
'        "emailAddress": "Bob.Smith@xyz.com",' & _
'        "displayName": "Bob Smith (BS)",' & _
'        "firstName": "Bob",' & _
'        "lastName": "Smith"' & _
'      },' & _
'      {' & _
'        "id": "000ca000-0d0a-0000-00d0-0e0a0f000000",' & _
'        "emailAddress": "Jane.Jones@xyz.com",' & _
'        "displayName": "Jane Jones (JJ)",' & _
'        "firstName": "Jane",' & _
'        "lastName": "Jones"' & _
'      }' & _
'   ]' & _
'  }' & _
'}'

Local $oJson = Json_Decode($json)
Local $x = 0

While 1
    $sDisplayName = Json_Get($oJson, '.result.participants[' & $x & '].displayName')
    If @error Then ExitLoop

    ConsoleWrite($sDisplayName & @CRLF)
    $x += 1
WEnd

that worked!! thank you for clarifying.  i thought json_decode outputs an array?  im pretty sure ive used it that way before - with a for loop to process all the $x instances

 

Link to comment
Share on other sites

7 hours ago, gcue said:

i thought json_decode outputs an array? 

json_decode returns the structure as it is mapped in the json-string.
If the outermost element in the json-string is an array definition, then json_decode returns an array.
On the other hand, if it is an object, then json-decode returns a Scripting.Dictionary object.
If the json-string is just a number, then json-decode just returns a number type.

The function json_decode maps the json-string into (nested) AutoIt data types.
Therefore, you must use the structure of the json-string as a guide when processing the output of json_decode.

Link to comment
Share on other sites

13 hours ago, AspirinJunkie said:

json_decode returns the structure as it is mapped in the json-string.
If the outermost element in the json-string is an array definition, then json_decode returns an array.
On the other hand, if it is an object, then json-decode returns a Scripting.Dictionary object.
If the json-string is just a number, then json-decode just returns a number type.

The function json_decode maps the json-string into (nested) AutoIt data types.
Therefore, you must use the structure of the json-string as a guide when processing the output of json_decode.

makes sense thank you for the info!

Link to comment
Share on other sites

Hello world!

I'm able to get Primary Sme and Secondary Sme but I am not sure why I can ONLY get the first instance of Other SME and Business Owner but not subsequent ones???  I know sometimes Other Sme is missing so not sure how if that's what's throwing things off.  Help is GREATLY appreciated!

#include "json.au3"

$json = '[{"Overview":{"Classification":"Application","Status":"Standard","Id":"000012","Name":"AP","AlternateName":"AP","Description":"11/30/2023","ManufacturerOrVendor":"AP","Type":"SaaS","Location":"Cloud","ReviewCycle":"Semi-annually","CreatedBy":"04/19/2013 12:06 PM","LastModifiedBy":"AN - 09/06/2022 12:55 PM"},"Ownership":{"PrimarySme":"AndyNa","SecondarySme":"KevTu","OtherSmes":["Ross"],"BusinessOwners":["Sam"],"AccessOwner":"Sam","AccessControllers":["Sam","KevYo","Ross"],"ItgManagers":["Don"],"Ward":"Cady","PortfolioSteward":"Dunlow"},"ReviewableSystems":{"InternetFacing":"No","GeneratesAutomatedEmail":"No","Is13":"No","IsSC1":"No","IsSC2":"No","Support":"No","Recorded":"No"}},{"Overview":{"Classification":"Application","Status":"Standard","Id":"000013","Name":"AE","AlternateName":"AE System","Description":"anlysis/troubleshooting.","ManufacturerOrVendor":"Internal","Type":"Custom","Location":"AP","ReviewCycle":"Semi-annually","CreatedBy":"05/22/2013 10:37 AM","LastModifiedBy":"12/05/2022 09:31 AM"},"Ownership":{"PrimarySme":"Jan","SecondarySme":"Paul","OtherSmes":[],"BusinessOwners":["Mike"],"AccessOwner":"Mike","AccessControllers":["Bran","Steve"],"ItgManagers":["Paul"],"Steward":"Cai","PortfolioSteward":"Osman"},"ReviewableSystems":{"InternetFacing":"No","GeneratesAutomatedEmail":"No","Is1":"No","Is1":"No","Is2":"No","Support":"No","Recorded":"No"}},{"Overview":{"Classification":"Application","Status":"Standard","Id":"0000178","Name":"AF","AlternateName":"AF Service","Description":"intermediary","ManufacturerOrVendor":"Internal","Type":"Custom","Location":"G","ReviewCycle":"Semi-annually","CreatedBy":"09/20/2011 10:40 AM","LastModifiedBy":"09/05/2022 10:38 PM"},"Ownership":{"PrimarySme":"Subra","SecondarySme":"Kumar","OtherSmes":["Rony"],"BusinessOwners":["Rei"],"AccessOwner":"Rei","AccessControllers":["Jay","Al","Sky"],"ItgManagers":["Jay","Sky"],"Steward":"Rei","PortfolioSteward":"Clark"},"ReviewableSystems":{"InternetFacing":"No","GeneratesAutomatedEmail":"No","Is1":"No","Is1":"No","Is2":"No","Support":"Yes","Recorded":"No"}}]'

$ojson = Json_Decode($json)

For $x = 0 To UBound($oJson) - 1
    $primary_sme = Json_Get($oJson, "[" & $x & "][Ownership.PrimarySme]")
    $secondary_sme = Json_Get($oJson, "[" & $x & "][Ownership.SecondarySme]")
    $other_sme = Json_Get($oJson, "[" & $x & "][Ownership.OtherSmes][" & $x & "]")

    $business_owner = Json_Get($oJson, "[" & $x & "][Ownership.BusinessOwners][" & $x & "]")

    ConsoleWrite("Primary SME: " & $primary_sme & @CRLF)
    ConsoleWrite("Secondary SME: " & $secondary_sme & @CRLF)
    ConsoleWrite("Other SME: " & $other_sme & @CRLF)

    ConsoleWrite("Business Owner: " & $business_owner & @CRLF & @CRLF)
Next

 

Edited by gcue
Link to comment
Share on other sites

OtherSmes is an array which in your example has only either 1 entry or none.
However, you pass $i as the index for this array - and this runs from 0 to 2.
Therefore, you only have a chance to get the value in the first loop pass where $i still has the value 0.
If you write it this way, however, you will get all the OtherSME from your example:

$other_sme = Json_Get($oJson, "[" & $x & "].Ownership.OtherSmes[0]")

I recommend you to visualize the JSON structure for yourself.
There are many online tools for that.
Then the structure becomes clearer.

Link to comment
Share on other sites

  • 2 months later...

I have a question what options are for $Option in Json_StringEncode($String, $Option = 0)

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

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...