mojomatt

Json Parsing Question

4 posts in this topic

Hi All,  

Can anyone help me figure out the syntax to use to get the jobid returned out of the below json string (in my code example)?  I want to use bracketed notation and I want the msgbox to display 2155813bb95e9829.

One example I've tried that doesn't work is...

$strJobIDFromJson = json_Get($objJson, "[jobid]")

 

 

I'm using the json.au3 include with these properties...

; File        : Json.au3 (2015.01.08)
; Purpose    : A Non-Strict JavaScript Object Notation (JSON) Parser UDF
; Author    : Ward
; Dependency: BinaryCall.au3
; Website    : http://www.json.org/index.html
;
; Source    : jsmn.c
; Author    : zserge
; Website    : http://zserge.com/jsmn.html
;
; Source    : json_string_encode.c, json_string_decode.c
; Author    : Ward

 

Here's my example code...

#Include <JSON.au3>
$strReturnedData2 = '{"jobid":{"2155813bb95e9829":{"startTime":"2016-10-28 20:56:53 UTC","requestor":"Requestor","description":"Description","email":"","content":[{"Name":"ContentName","Parameters":""}],"computers":{"Computername":{"overallStatus":"Waiting for client to check-in...","details":[{"name":"DetailsName","env":"","actionID":"","status":"","exitCode":"","lastLine":"","startTime":"","endTime":"","contentURL":""}]}},"actionStatus":{"iem-dev":"Open"}}},"status_text":"","error_text":"","status_code":"200","status":"OK","rc":"0"}'
$objJson = json_Decode($strReturnedData2)
$strJobIDFromJson = json_Get($objJson, What Do I Put Here?)
MsgBox(0,"JobID",$strJobIDFromJson)

 

Thanks

 

 

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Hello. You can do this.

#include <JSON.au3>
Local $strReturnedData2 = '{"jobid":{"2155813bb95e9829":{"startTime":"2016-10-28 20:56:53 UTC","requestor":"Requestor","description":"Description","email":"","content":[{"Name":"ContentName","Parameters":""}],"computers":{"Computername":{"overallStatus":"Waiting for client to check-in...","details":[{"name":"DetailsName","env":"","actionID":"","status":"","exitCode":"","lastLine":"","startTime":"","endTime":"","contentURL":""}]}},"actionStatus":{"iem-dev":"Open"}}},"status_text":"","error_text":"","status_code":"200","status":"OK","rc":"0"}'
Local $objJson = json_Decode($strReturnedData2)
Local $strJobIDFromJson = json_Get($objJson, '["jobid"]').Keys[0]
ConsoleWrite($strJobIDFromJson & @CRLF)

 

Saludos

Edited by Danyfirex

Share this post


Link to post
Share on other sites

Alternatively you could use a regular expression

$strReturnedData2 = '{"jobid":{"2155813bb95e9829":{"startTime":"2016-10-28 20:56:53 UTC","requestor":"Requestor","description":"Description","email":"","content":[{"Name":"ContentName","Parameters":""}],"computers":{"Computername":{"overallStatus":"Waiting for client to check-in...","details":[{"name":"DetailsName","env":"","actionID":"","status":"","exitCode":"","lastLine":"","startTime":"","endTime":"","contentURL":""}]}},"actionStatus":{"iem-dev":"Open"}}},"status_text":"","error_text":"","status_code":"200","status":"OK","rc":"0"}'

$jobid = StringRegExpReplace($strReturnedData2, '.*"jobid":\{"([^"]+).*', "$1")
MsgBox(0, "JobID", $jobid)

 

Share this post


Link to post
Share on other sites

Thanks Danyfirex that syntax works.  :)

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

    • ur
      By ur
      I have a github repository and when I run the below command it will retrieve a json file.
      curl --user "user:password" https://api.github.com/repos/ukreddy-erwin/Build-war/commits > Desktop/uday.html The output json file will be of the below format.
      [ { "sha": "525ddee5f25628f89c04980d7f683e9cd8f56b7a", "commit": { "author": { "name": "ukreddy", "email": "ukreddy@erwin.com", "date": "2016-12-26T12:27:14Z" }, "committer": { "name": "ukreddy", "email": "ukreddy@erwin.com", "date": "2016-12-26T12:27:14Z" }, "message": "changed gwt and gxt folder structure to build.xml", "tree": { "sha": "8d4f2cbca93efec18be8a17f25f78ad168e65347", "url": "https://api.github.com/repos/ukreddy-erwin/Build-war/git/trees/8d4f2cbca93efec18be8a17f25f78ad168e65347" }, "url": "https://api.github.com/repos/ukreddy-erwin/Build-war/git/commits/525ddee5f25628f89c04980d7f683e9cd8f56b7a", "comment_count": 0 }, "url": "https://api.github.com/repos/ukreddy-erwin/Build-war/commits/525ddee5f25628f89c04980d7f683e9cd8f56b7a", "html_url": "https://github.com/ukreddy-erwin/Build-war/commit/525ddee5f25628f89c04980d7f683e9cd8f56b7a", "comments_url": "https://api.github.com/repos/ukreddy-erwin/Build-war/commits/525ddee5f25628f89c04980d7f683e9cd8f56b7a/comments", "author": { "login": "ukreddy-erwin", "id": 21240709, "avatar_url": "https://avatars.githubusercontent.com/u/21240709?v=3", "gravatar_id": "", "url": "https://api.github.com/users/ukreddy-erwin", "html_url": "https://github.com/ukreddy-erwin", "followers_url": "https://api.github.com/users/ukreddy-erwin/followers", "following_url": "https://api.github.com/users/ukreddy-erwin/following{/other_user}", "gists_url": "https://api.github.com/users/ukreddy-erwin/gists{/gist_id}", "starred_url": "https://api.github.com/users/ukreddy-erwin/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ukreddy-erwin/subscriptions", "organizations_url": "https://api.github.com/users/ukreddy-erwin/orgs", "repos_url": "https://api.github.com/users/ukreddy-erwin/repos", "events_url": "https://api.github.com/users/ukreddy-erwin/events{/privacy}", "received_events_url": "https://api.github.com/users/ukreddy-erwin/received_events", "type": "User", "site_admin": false }, "committer": { "login": "ukreddy-erwin", "id": 21240709, "avatar_url": "https://avatars.githubusercontent.com/u/21240709?v=3", "gravatar_id": "", "url": "https://api.github.com/users/ukreddy-erwin", "html_url": "https://github.com/ukreddy-erwin", "followers_url": "https://api.github.com/users/ukreddy-erwin/followers", "following_url": "https://api.github.com/users/ukreddy-erwin/following{/other_user}", "gists_url": "https://api.github.com/users/ukreddy-erwin/gists{/gist_id}", "starred_url": "https://api.github.com/users/ukreddy-erwin/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ukreddy-erwin/subscriptions", "organizations_url": "https://api.github.com/users/ukreddy-erwin/orgs", "repos_url": "https://api.github.com/users/ukreddy-erwin/repos", "events_url": "https://api.github.com/users/ukreddy-erwin/events{/privacy}", "received_events_url": "https://api.github.com/users/ukreddy-erwin/received_events", "type": "User", "site_admin": false }, "parents": [ { "sha": "db4d61c5bbef555e6cc9f2e852aaf9d75772475c", "url": "https://api.github.com/repos/ukreddy-erwin/Build-war/commits/db4d61c5bbef555e6cc9f2e852aaf9d75772475c", "html_url": "https://github.com/ukreddy-erwin/Build-war/commit/db4d61c5bbef555e6cc9f2e852aaf9d75772475c" } ] } ] So, I need to parse above file and get the number of opening and closing brackets {} .
      So that would be the number of commits in the repository.
      Any suggestion on how to parse this file of json format.
    • uncommon
      By uncommon
      So I started using Json.au3 (2015.01.08) by Ward. Pretty good but I am having some real trouble figuring out how to remove a certain key.
      There is an internal function called Json_ObjDelete which seems to use a Scripting.Dictionary Object this uses $Object.Remove($Key)
      but this will only remove the first level key. For example if I use $Object.Remove('foo') in a json string like this...
      {"foo":"foo","bar":["bar"],"test":["",{"foo":{"bar":["","",{"foo":{"bar":"Test"}}]}}]}
      It will reduce do this...
      {"bar":["bar"],"test":["",{"foo":{"bar":["","",{"foo":{"bar":"Test"}}]}}]}
      So my question is how do I get to the next 'foo' and remove it because it does not seem to recognize others as a key?
      Thank you for your time.
    • sivaramanm
      By sivaramanm
      Have this following input parameter(Complex list of inputs) that need to be SEND as part of HTTP POST Request. 
      Have been searching forums to find an AutoIT equivalent to enapsulate the following data, but unsuccessful.
      Below given Working Code is failing with 400-Bad Request for obvious reason of incomplete input - unable to send ip_list and other array type parameters
      Questions:
      1. How to encapsulate the below given data for $oHttp.Send()
      2. How to enapsulate special data types like
       null - aligned_device_tempate parameter
      White sapced values - () and
      empty array? - hostname or device_groups
       
      Input Parameter in JSON format to be converted & sent in AutoIT compatible
      {       "name": "SnmpSIM",       "description": "EM7 device created by BDD test case",       "credentials":"{{feature.credential.body.result_set[*].URI}}",        "organization": "/api/organization/0",       "aligned_device_template": null,       "aligned_collector": "{{feature.appliance_id[0].id[0]}}{{feature.appliance_id[0].id[1]}}",       "discover_non_snmp": "1",       "scan_ports": [         "21",         "22",         "23",         "25",         "80"       ],       "ip_lists": [         {         "start_ip": "{{feature.json.ip}}",         "end_ip": "{{feature.json.ip}}"         }       ],       "dhcp_enabled": "0",       "duplicate_protection": "1",       "model_device": "1",       "log_all": "1",       "scan_all_ips": null,       "port_scan_timeout": null,       "initial_scan_level": null,       "scan_throttle": null,       "interface_inventory_timeout": "600000",       "max_interface_inventory_count": "10000",       "bypass_interface_inventory": "0",       "hostnames": [],       "device_groups": []     }  
      Working Code
      ; The data to be sent $sPD = 'name=SnmpSIM&description=EM7 device created by BDD test case&credentials=37&organization=/api/organization/0&aligned_device_template=null&aligned_collector=1&discover_non_snmp=1&dhcp_enabled=0&duplicate_protection=1&model_device=1&log_all=1&scan_all_ips= null&port_scan_timeout= null&initial_scan_level= null&scan_throttle= null&interface_inventory_timeout=600000&max_interface_inventory_count=10000&bypass_interface_inventory=0&hostnames=&device_groups=&scan_ports=21' ; Creating the object $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("POST", "http://10.2.4.18/api/discovery_session", False) $oHTTP.SetCredentials("username","password",0) $oHTTP.SetRequestHeader("Content-Type", "application/em7-resource-uri") ; Performing the Request $oHTTP.Send($sPD) ; Download the body response if any, and get the server status response code. $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status If $oStatusCode <> 200 then  MsgBox(4096, "Response code", $oStatusCode) EndIf ; Saves the body response regardless of the Response code  $file = FileOpen("Received.html", 2) ; The value of 2 overwrites the file if it already exists  FileWrite($file, $oReceived)  FileClose($file)  

       SAMPLE VBA CODE for Reference
       Dim Items As New Collection  Dim Item As Dictionary  Dim Id As Long  For Id = 1 To 2      Set Item = New Dictionary      Item("iditem") = Id      Item("amount") = 1      Items.Add Item  Next Id  Request.AddBodyParameter "id", 5633  Request.AddBodyParameter "items", Items $oDictionary = ObjCreate("Scripting.Dictionary") $oDictionary.ADD("start_ip", "10.20.7.31") $oDictionary.ADD("end_ip", "10.20.7.33")  
    • Altor
      By Altor
      Hi all:
      I have a small problem with Curl syntax to send a POST to a CouchDB database.
      I want send this:
      -H Content-type: application/json -X POST http://127.0.0.1:5984/test -d {"title": "pencil"} but this code does not work:
      $code ='curl.exe -H Content-type: application/json -X POST http://127.0.0.1:5984/test -d {"title": "pencil"}' Run(@ComSpec & " /k " & $code,"",@SW_HIDE) but to work I have to format the line like this:
      $code = 'curl -H "Content-Type: application/json" -X POST "http://127.0.0.1:5984/test" -d "{\"title\":\"pencil\"}"' Run(@ComSpec & " /k " & $code,"",@SW_HIDE) my question is whether this is the most correct way to write the correct code using the additional signs "  and  \   or is there some other more elegant way to do the same.
      Thank's
    • Ward
      By Ward
      Introduction
      "MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller." (by http://msgpack.org/).
      There are already so many languages support MessagePack format, here comes AutoIt version. The backend coder is Charlie Gunyon's cmp. It supported MessagePack proposal v5.
      This UDF only have two public functions: MsgPack_Pack() and MsgPack_Unpack(). It just like Json_Enocde() and Json_Decode() in my ?do=embed' frameborder='0' data-embedContent>>JSON UDF. The Map type will  be decoded into "Windows Scripting Dictionary Object" retuned from ObjCreate("Scripting.Dictionary"). So I suggest using Json.au3 to deal with the Map/Object data type. The main difference is MessagePack support Binary format, but Json not. For example (?do=embed' frameborder='0' data-embedContent>>Json.au3 is required to run this example):
      Local $Obj1 Json_Put($Obj1, ".binary", Binary("0x00")) Json_Put($Obj1, ".string", "abc") Json_Put($Obj1, ".int", Random(0, 1000, 1)) Json_Put($Obj1, ".float", Random()) Json_Put($Obj1, ".bool", True) Json_Put($Obj1, ".null", Null) Local $Binary = MsgPack_Pack($Obj1) Local $Obj2 = MsgPack_Unpack($Binary) ConsoleWrite("Test2 $Obj1.binary is " & VarGetType(Json_Get($Obj2, ".binary")) & @LF) ; "Binary" In my opinion, for human readable data storing or exchanging, of course choose Json. Otherwise, especially to exchange data on the internet, MessagePack may be a better choice. 
      MsgPack.zip