Jump to content
ur

How to get number of sections in JSON file

Recommended Posts

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.

Share this post


Link to post
Share on other sites
ur

This is the equivalent GET command of GitHub API.

GET /repos/:owner/:repo/commits

 

Edited by ur

Share this post


Link to post
Share on other sites
careca
Quote

get the number of opening and closing brackets {}

StringInStr can find those, and retrieves the position.


Spoiler

Paster - Main function is to paste text, but has more functions. (No longer mantained, switched to String Trigger)

OpenW - Open With... alternative, Open any file with any application, set it's icon, set application as default.

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Firefox Profile Backup - Backup/restore previously saved profile.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Share this post


Link to post
Share on other sites
ur

No I just need the count...Like number of sets...Is there any UDF for Json Files?

 

Edited by ur

Share this post


Link to post
Share on other sites
mLipok
_Example()
Func _Example()
    Local $sJSON = ClipGet()
    StringReplace($sJSON,'{','')
    ConsoleWrite("! { count=" & @extended & @CRLF)
    StringReplace($sJSON,'}','')
    ConsoleWrite("! } count=" & @extended & @CRLF)
EndFunc

 

  • Like 1

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for 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 API *

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 *

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 * 

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) * 

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 *

"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: 2018-03-17

Share this post


Link to post
Share on other sites
ur

May be this is wrong now.
But I got below input from support team that.

 

WHen we run the curl command differently as below.

we can get the total count of commits by looking at the Link header when making a request with only 1 commit per page.
For example, here's a request to the Linguist repository:
curl -I https://api.github.com/repos/github/linguist/commits?per_page=1.


Looking at our Link header, you can see the last page value:
Link: <https://api.github.com/repositories/1725199/commits?per_page=1&page=2>; rel="next", <https://api.github.com/repositories/1725199/commits?per_page=1&page=5454>; rel="last"
Since the last page is 5454, this means that there are a total of 5454 commits in that repository
 

How to get this number by parsing the output.

Share this post


Link to post
Share on other sites
ur

This is the command we can run for example.

curl -I https://api.github.com/repos/github/linguist/commits?per_page=1

And the command output is as below.

HTTP/1.1 200 OK
Server: GitHub.com
Date: Thu, 29 Dec 2016 10:17:35 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 3448
Status: 200 OK
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 57
X-RateLimit-Reset: 1483009802
Cache-Control: public, max-age=60, s-maxage=60
Vary: Accept
ETag: "9120c8c80a4342a0b46cad7086358638"
Last-Modified: Thu, 01 Jan 1970 00:00:00 GMT
X-GitHub-Media-Type: github.v3; format=json
Link: <https://api.github.com/repositories/1725199/commits?per_page=1&page=2>; rel="next", <https://api.github.com/repositories/1725199/commits?per_page=1&page=5454>; rel="last"
Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin: *
Content-Security-Policy: default-src 'none'
Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
X-Content-Type-Options: nosniff
X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
Vary: Accept-Encoding
X-Served-By: edf23fdc48375d9066b698b8d98062e9
X-GitHub-Request-Id: 673CD4B2:772D:DC0C69D:5864E2BF

So, if we observe the Link: line above, the number 5454 is visible, how to read this number from the output.?

 

Can anyone suggest that.

Share this post


Link to post
Share on other sites
careca

If it's only that output maybe you can do a regex that uses that '&page=' '>;' and get what's in the middle.


Spoiler

Paster - Main function is to paste text, but has more functions. (No longer mantained, switched to String Trigger)

OpenW - Open With... alternative, Open any file with any application, set it's icon, set application as default.

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Firefox Profile Backup - Backup/restore previously saved profile.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Share this post


Link to post
Share on other sites
ur

I didn't get chance to work on regular expressions before.

Can you share me any references.

Share this post


Link to post
Share on other sites
mLipok
3 hours ago, ur said:

May be this is wrong now.
But I got below input from support team that.

 

WHen we run the curl command differently as below.

we can get the total count of commits by looking at the Link header when making a request with only 1 commit per page.
For example, here's a request to the Linguist repository:
curl -I https://api.github.com/repos/github/linguist/commits?per_page=1.


Looking at our Link header, you can see the last page value:
Link: <https://api.github.com/repositories/1725199/commits?per_page=1&page=2>; rel="next", <https://api.github.com/repositories/1725199/commits?per_page=1&page=5454>; rel="last"
Since the last page is 5454, this means that there are a total of 5454 commits in that repository
 

How to get this number by parsing the output.

This look like in TeamViewer API (look in my signature).
When github have to many information to send to you, then github is splitting this data into pages.
You should get each page and parse them in a loop.

btw.
I think you should try to use WinHTTP instead CURL, but for now I want to ask how you use CURL with AutoIt ?

 

Edited by mLipok

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for 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 API *

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 *

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 * 

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) * 

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 *

"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: 2018-03-17

Share this post


Link to post
Share on other sites
JohnQSmith

I'm guessing you're using CURL because you have either Cygwin or are using Windows 10's Subsystem for Linux. Here's a quick solution using that...

curl --silent -I https://api.github.com/repos/github/linguist/commits?per_page=1 | grep "^Link" | sed -e 's/.*page=\([0-9]*\)>; rel=\"last.*/\1/'

 

Edited by JohnQSmith
Trying to remove syntax highlighting

Whenever someone says "pls" because it's shorter than "please", I say "no" because it's shorter than "yes".

Share this post


Link to post
Share on other sites
JohnQSmith

Here it is using WinHTTP as suggested by @mLipok

$oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
$oHTTP.Open("GET", "http://api.github.com/repos/github/linguist/commits?per_page=1")
$oHTTP.Send()
$header = $oHTTP.Getresponseheader("Link")
$numCommits = StringRegExpReplace( $header, '.*page=([0-9]+)>; rel="las.*', '$1' )
ConsoleWrite($numCommits)

 


Whenever someone says "pls" because it's shorter than "please", I say "no" because it's shorter than "yes".

Share this post


Link to post
Share on other sites
ur

This is my solution for this....using curl command

;#include "ProcessEx.au3"
#include "ProcessEx_AddedNewEntryForLogging.au3"
#include <Array.au3>
#include <WinAPIFiles.au3>

Func NoChangesRequired($sBuildCommand = 'curl -I --user "userid:password" https://api.github.com/repos/erwin-inc/erwin-main/commits?per_page=1',$commitfile = @TempDir&"\git_erwin_commit.txt")

$valueRead = ProcessGitCommitCount($sBuildCommand)

If not FileExists($commitfile) Then
    FileWrite($commitfile,$valueRead)
    ;MsgBox(0,"","Changes are there.")
    return False
ELse
     Local $hFileOpen = FileOpen($commitfile, $FO_READ)
     If $hFileOpen = -1 Then
        ;MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.")
        Return False
     EndIf

     ; Read the fist line of the file using the handle returned by FileOpen.
    Local $sFileRead = FileReadLine($hFileOpen, 1)

    ; Close the handle returned by FileOpen.
    FileClose($hFileOpen)
    If Number(StringStripWS($sFileRead,$STR_STRIPLEADING + $STR_STRIPTRAILING))= Number($valueRead) Then
        ;MsgBox(0,"","No change in commit")
        Return True
    Else
        ;MsgBox(0,"","Changes are there")
        FileDelete($commitfile)
        FileWrite($commitfile,$valueRead)
        Return False
    EndIf

EndIf

EndFunc

Func ProcessGitCommitCount($sBuildCommand)
$sOutput = _Process_RunCommand($PROCESS_RUNWAIT, $PROCESS_COMMAND & """" &$sBuildCommand &"""") ; Record the output
$Ret = @extended ; Note the exit code
;MsgBox(0,$Ret,$sOutput)
Local $strTemp = StringSplit($sOutput, @CRLF,$STR_ENTIRESPLIT)
;_ArrayDisplay($strTemp)


$u = ""
For $vElement In $strTemp
        ;$sString = $sString & $vElement & @CRLF

        If StringInStr($vElement,"Link:") then
            $u = $vElement
            ExitLoop
        EndIf

Next

$u = StringStripWS($u,$STR_STRIPLEADING + $STR_STRIPTRAILING)
If StringLen($u)=0 Then
    ;MsgBox(0,"","No output from GitHub")
    return "No output"
ElseIf StringInStr($u,"Link:") Then
    return ProcessHeader($u)
Else
    ;MsgBox(0,"","Some random unnecessary output")
    return "Some random unnecessary output"
EndIf
EndFunc

;to remove any empty strings in array and reduce its size
Func RemoveEmptyArrayValues(ByRef $arrLines)
  $intCount = 1
  While $intCount < UBound($arrLines)
         $arrLines[$intCount] = StringStripWS($arrLines[$intCount],$STR_STRIPLEADING + $STR_STRIPTRAILING)
         If StringLen($arrLines[$intCount])=0 Then
            _ArrayDelete($arrLines, $intCount)
            $intCount = $intCount - 1
         EndIf
         $intCount = $intCount + 1
   WEnd
EndFunc

Func RemoveOtherData(ByRef $arrLines)
  $intCount = 1
  While $intCount < UBound($arrLines)
         $arrLines[$intCount] = StringStripWS($arrLines[$intCount],$STR_STRIPLEADING + $STR_STRIPTRAILING)
         If StringInStr($arrLines[$intCount],">;") Then
             $arrLines[$intCount] = StringTrimRight($arrLines[$intCount], 2)
         Else
            _ArrayDelete($arrLines, $intCount)
            $intCount = $intCount - 1
         EndIf
         $intCount = $intCount + 1
   WEnd
EndFunc

Func ProcessHeader($header)
     $splittedArray = StringSplit ( $header, "per_page=1&page=" )
     ;_ArrayDisplay($splittedArray)
     RemoveEmptyArrayValues($splittedArray)
     ;_ArrayDisplay($splittedArray)
     RemoveOtherData($splittedArray)
     ;_ArrayDisplay($splittedArray)
     ;MsgBox(0,"",$splittedArray[UBound($splittedArray)-1])
     return $splittedArray[UBound($splittedArray)-1]
EndFunc

 

Edited by ur

Share this post


Link to post
Share on other sites
ur
On 12/29/2016 at 7:37 PM, mLipok said:

This look like in TeamViewer API (look in my signature).
When github have to many information to send to you, then github is splitting this data into pages.
You should get each page and parse them in a loop.

btw.
I think you should try to use WinHTTP instead CURL, but for now I want to ask how you use CURL with AutoIt ?

 

Can you help me how to use WinHTTP so that I can use them in later scripts.

And I used CURL by the UDF mentioned above

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

    • Ward
      By Ward
      Introduction
      JSON (Javascript Object Notation) is a popular data-interchange format and supported by a lot of script languages. On AutoIt, there is already a >JSON UDF written by Gabriel Boehme. It is good but too slow, and not supports unicode and control characters very well. So I write a new one (and of course, fast one as usual).

      I use a machine code version of JSON parser called "jsmn". jsmn not only supports standard JSON, but also accepts some non-strict JSON string. See below for example.
       
      Important Update!!
      I rename the library from jsmn.au3 to json.au3. All function names are changed, too.
       
      Decoding Function
      Json_Decode($Json) $Json can be a standard or non-standard JSON string. For example, it accepts:
      { server: example.com port: 80 message: "this looks like a config file" } The most JSON data type will be decoded into corresponding AutoIt variable, including 1D array, string, number, true, false, and null. JSON object will be decoded into "Windows Scripting Dictionary Object" retuned from ObjCreate("Scripting.Dictionary"). AutoIt build-in functions like IsArray, IsBool, etc. can be used to check the returned data type. But for Object and Null, Json_IsObject() and Json_IsNull() should be used.

      If the input JSON string is invalid, @Error will be set to $JSMN_ERROR_INVAL. And if the input JSON string is not finish (maybe read from stream?), @Error will be set to $JSMN_ERROR_PART.

      Encoding Function
      Json_Encode($Data, $Option = 0, $Indent = "\t", $ArraySep = ",\r\n", $ObjectSep = ",\r\n", $ColonSep = ": ") $Data can be a string, number, bool, keyword(default or null), 1D arrry, or "Scripting.Dictionary" COM object. Ptr will be converted to number, Binary will be converted to string in UTF8 encoding. Other unsupported types like 2D array, dllstruct or object will be encoded into null.

      $Option is bitmask consisting following constant:
      $JSON_UNESCAPED_ASCII ; Don't escape ascii charcters between chr(1) ~ chr(0x1f) $JSON_UNESCAPED_UNICODE ; Encode multibyte Unicode characters literally $JSON_UNESCAPED_SLASHES ; Don't escape / $JSON_HEX_TAG ; All < and > are converted to \u003C and \u003E $JSON_HEX_AMP ; All &amp;amp;amp;amp;s are converted to \u0026 $JSON_HEX_APOS ; All ' are converted to \u0027 $JSON_HEX_QUOT ; All " are converted to \u0022 $JSON_PRETTY_PRINT ; Use whitespace in returned data to format it $JSON_STRICT_PRINT ; Make sure returned JSON string is RFC4627 compliant $JSON_UNQUOTED_STRING ; Output unquoted string if possible (conflicting with $JSMN_STRICT_PRINT) Most encoding option have the same means like PHP's json_enocde() function. When $JSON_PRETTY_PRINT is set, output format can be change by other 4 parameters ($Indent, $ArraySep, $ObjectSep, and $ColonSep). Because these 4 output format parameters will be checked inside Jsmn_Encode() function, returned string will be always accepted by Jsmn_Decode(). $JSON_UNQUOTED_STRING can be used to output unquoted string that also accetped by Jsmn_Decode().

      $JSON_STRICT_PRINT is used to check output format setting and avoid non-standard JSON output. So this option is conflicting with $JSON_UNQUOTED_STRING.

      Get and Put Functions
      Json_Put(ByRef $Var, $Notation, $Data, $CheckExists = False) Json_Get(ByRef $Var, $Notation) These functions helps user to access object or array more easily. Both dot notation and square bracket notation can be supported. Json_Put() by default will create non-exists objects and arrays. For example:
      Local $Obj Json_Put($Obj, ".foo", "foo") Json_Put($Obj, ".bar[0]", "bar") Json_Put($Obj, ".test[1].foo.bar[2].foo.bar", "Test") Local $Test = Json_Get($Obj, '["test"][1]["foo"]["bar"][2]["foo"]["bar"]') ; "Test" Object Help Functions
      Json_ObjCreate() Json_ObjPut(ByRef $Object, $Key, $Value) Json_ObjGet(ByRef $Object, $Key) Json_ObjDelete(ByRef $Object, $Key) Json_ObjExists(ByRef $Object, $Key) Json_ObjGetCount(ByRef $Object) Json_ObjGetKeys(ByRef $Object) Json_ObjClear(ByRef $Object) These functions are just warps of "Scripting.Dictionary" COM object. You can use these functions if you are not already familiar with it.
       
      == Update 2013/05/19 ==
       
      * Add Jsmn_Encode() option "$JSMN_UNESCAPED_ASCII". Now the default output of Json_Encode() is exactly the same as PHP's json_encode() function (for example, chr(1) will be encoded into u0001).
      $JSON_UNESCAPED_ASCII ; Don't escape ascii charcters between chr(1) ~ chr(0x1f)  
      == Update 2015/01/08 ==
      * Rename the library from jsmn.au3 to json.au3. All function names are changed, too.
      * Add Json_Put() and Json_Get()
      * Add Null support
      * Using BinaryCall.au3 to loading the machine code.
       
      == Update 2018/01/13=   Jos
      * Add JsonDump() to list all Json Keys and their values to easily figure out what they are.

      JSMN.zip
      JSMN.zip
      Json.zip
      Json(2018.01.13).zip
    • 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!!
×