Jump to content
Sign in to follow this  
ur

How to get number of sections in JSON file

Recommended Posts

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

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
Quote

get the number of opening and closing brackets {}

StringInStr can find those, and retrieves the position.


Spoiler

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

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

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.

Inconspicuous - Hide files in plain sight, not fully encrypted.

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.

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

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
_Example()
Func _Example()
    Local $sJSON = ClipGet()
    StringReplace($sJSON,'{','')
    ConsoleWrite("! { count=" & @extended & @CRLF)
    StringReplace($sJSON,'}','')
    ConsoleWrite("! } count=" & @extended & @CRLF)
EndFunc

 


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
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 APIErrorLog.au3 UDF - A logging Library *

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 * 

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 TaskScheduler

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: 2019-10-01

Share this post


Link to post
Share on other sites

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

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

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


Spoiler

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

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

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.

Inconspicuous - Hide files in plain sight, not fully encrypted.

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.

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

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
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 beginning - communication with GitHub REST API Forum Rules *
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 APIErrorLog.au3 UDF - A logging Library *

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 * 

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 TaskScheduler

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: 2019-10-01

Share this post


Link to post
Share on other sites

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

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

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
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
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By argumentum
      #include <SQLite.au3> ;-- When SQLite is compiled with the JSON1 extensions it provides builtin tools ;-- for manipulating JSON data stored in the database. ;-- This is a gist showing SQLite return query as a JSON object. ;-- https://www.sqlite.org/json1.html Example() Func Example() _SQLite_Startup() ; "<your path>\sqlite3.dll", False, 1) ; https://www.autoitscript.com/autoit3/docs/libfunctions/_SQLite_Startup.htm _SQLite_Open() ; ...if you can not run this due to errors, get the latest DLL from https://www.sqlite.org/ If _SQLite_Exec(-1, "CREATE TABLE users (id INTEGER PRIMARY KEY NOT NULL, full_name TEXT NOT NULL, email TEXT NOT NULL, created DATE NOT NULL );") Then Return 4 If _SQLite_Exec(-1, 'INSERT INTO users VALUES ' & _ '(1, "Bob McFett", "bmcfett@hunters.com", "32-01-01"),' & _ '(2, "Angus O''Vader","angus.o@destroyers.com", "02-03-04"),' & _ '(3, "Imperator Colin", "c@c.c", "01-01-01");') Then Return 5 ; -- Get query data as a JSON object using the ; -- json_group_object() [1] and json_object() [2] functions. _SQLite_GetTable2d_ArrayToConsole("SELECT" & _ " json_group_object(" & _ " email," & _ " json_object('full_name', full_name, 'created', created)" & _ " ) AS json_result" & _ " FROM (SELECT * FROM users WHERE created > ""02-01-01"");") ; {"bmcfett@hunters.com":{"full_name":"Bob McFett","created":"32-01-01"},"angus.o@destroyers.com":{"full_name":"Angus O'Vader","created":"02-03-04"}} ; -- Get query data as a JSON object using the ; -- json_group_array() function to maintain order. _SQLite_GetTable2d_ArrayToConsole("SELECT" & _ " json_group_array(" & _ " json_object('full_name', full_name, 'created', created)" & _ " ) AS my_json_result_OrAnythingReally" & _ " FROM (SELECT * FROM users ORDER BY created);") ; [{"full_name":"Imperator Colin","created":"01-01-01"},{"full_name":"Angus O'Vader","created":"02-03-04"},{"full_name":"Bob McFett","created":"32-01-01"}] ;-- Links ;-- [1] https://www.sqlite.org/json1.html#jgroupobject ;-- [2] https://www.sqlite.org/json1.html#jobj ; example found at https://gist.github.com/akehrer/481a38477dd0518ec0086ac66e38e0e2 EndFunc ;==>Example Func _SQLite_GetTable2d_ArrayToConsole($sSQL, $hDB = -1) Local $aResult, $iRows, $iColumns If _SQLite_GetTable2d($hDB, $sSQL, $aResult, $iRows, $iColumns) Then ConsoleWrite("! SQLite Error: " & _SQLite_ErrCode($hDB) & @CRLF & "! " & _SQLite_ErrMsg($hDB) & @CRLF) Else _SQLite_Display2DResult($aResult) EndIf ConsoleWrite(@CRLF) EndFunc ;==>_SQLite_GetTable2d_ArrayToConsole Based on this example, you can build your own query. 
      The code has all the explanations.
      Enjoy  
    • By matwachich
      Hi AutoIters!
      Here is my new UDF about GUIs: it's an enhanced mixture of Advanced InputBox (deprecated) and KODA Parser (deprecated), with additional functions.
      What you can do with it:
      Parse KODA files and directly create GUIs (_GUIUtils_CreateFromKODA) Parse a simple JSON form definition to simply create advanced InputBoxes with any amount/type of input controls (_GUIUtils_CreateFromJSON) Created GUIs are returned as Scripting.Dictionary objects, and you have helper functions to access GUIs controls by their names (_GUIUtils_HWnd, _GUIUtils_CtrlID, _GUIUtils_HCtrl ...) A function that can make a GUI created from KODA/JSON (defined by it's $oForm object) and make it a modal InputDialogBox (just like InputBox, but returns all entered data as Scripting.Dictionary object) Functions are documented, and there are some examples.
      Consider this UDF as beta, but since I'm currently using it in a small commercial project, it should become production ready in near future.
      To always get the latest code version, get it from Github (more up to date than this topic).
      Update 04/02/2020:
      New simple application example Fixed focused control handling in _GUIUtils_InputDialog Reset input values before returning from _GUIUtils_InputDialog Fixed CloseOnEsc in _GUIUtils_InputDialog Fixed Input not reset Fixed all ListBox items are selected Project now on GitHub https://github.com/matwachich/autoit-guiutils/
      Update 05/02/2020:
      Support for nodate for Date and Time input controls (pass null value) New handling of focused control _GUIUtils_InputDialog: Now, you can specify the focused control in $oInitialData by setting "controlName:focus" = True Updated documentation of _GUIUtils_InputDialog Update 07/02/2020:
      Bug corrected when setting Data input control Added: abillity to read a single input control New functions (_GUIUtils_GetInputs, _GUIUtils_WriteInputs), documentation completion. Readme file and screenshots on Github Page  
      GUIUtils.zip
    • By Roy_
      Ciao,
      This example reproduces the problem I encounter when sending a post request to an echo server.
      Instead of being sent as text utf8, the data is transmitted base64 encoded.
      Example:
      - json String: '{"firstName":"Jonathan","lastName":"Freeman","loginCount":4,"active": "yes","text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel volutpat nunc. Maecenas id tempus mi. Morbi ipsum enim, ultricies ac augue sit amet, ullamcorper finibus ex. Vestibulum vel posuere nibh, nec faucibus eros. Nam malesuada non lacus a suscipit. Nulla rhoncus tempus mi quis placerat. Curabitur commodo tincidunt justo quis sollicitudin."}'
      - server response: "data:application/octet-stream;base64,AAAAALgE6QNYAIAAAgAAANQCAAAAAAAAWF8AAAAAAAD0VQAAAAAAAD9APQAAAAAAAwAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAABBAAAAAAABRUAAAAmIZwcAbRt8/LMa9UAAAAAAAAAAGFzIGlkIHRlbXB1cyBtaS4gTW9yYmkgaXBzdW0gZW5pbSwgdWx0cmljaWVzIGFjIGF1Z3VlIHNpdCBhbWV0LCB1bGxhbWNvcnBlciBmaW5pYnVzIGV4LiBWZXN0aWJ1bHVtIHZlbCBwb3N1ZXJlIG5pYmgsIG5lYyBmYXVjaWJ1cyBlcm9zLiBOYW0gbWFsZXN1YWRhIG5vbiBsYWN1cyBhIHN1c2NpcGl0LiBOdWxsYSByaG9uY3VzIHRlbXB1cyBtaSBxdWlzIHBsYWNlcmF0LiBDdXJhYml0dXIgY29tbW9kbyB0aW5jaWR1bnQganVzdG8gcXVpcyBzb2xsaWNpdHVkaW4uIn0="
       
      How can I go about transmitting data in text format utf8?
      Thanks in advance for the help.
      In the zip file:
      - CurlJsonPost.au3: this script
      - Curl.au3: UDF by Ward (thank you!)
      - data.json: json srting for command line test
       
      Note: using Curl.exe with json string saved in a file (utf8 encoded) named data.json, works perfectly
      To try with the command line tool:
      - save data.json in curl\bin directory
      - open cmd.exe and cd to curl\bin directory
      - Enter the following command:
      curl -H "Content-Type: application/json" --data @data.json https://httpbin.org/post
       
      #Include "Curl.au3" Global $_cURL_OutputBuffer Local $sJson = '{"firstName":"Jonathan","lastName":"Freeman","loginCount":4,"active": "yes","text":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel volutpat nunc. Maecenas id tempus mi. Morbi ipsum enim, ultricies ac augue sit amet, ullamcorper finibus ex. Vestibulum vel posuere nibh, nec faucibus eros. Nam malesuada non lacus a suscipit. Nulla rhoncus tempus mi quis placerat. Curabitur commodo tincidunt justo quis sollicitudin."}' Local $iRetCode, $sServerResponse ConsoleWrite("=== Json post test ===" & @LF) ConsoleWrite(StringFormat("Retcode: %s - %s", $iRetCode, Curl_Easy_strerror($iRetCode)) & @LF) ConsoleWrite("Data returned from server" & @LF & @LF) $sServerResponse = JsonPost_Test($sJson, $iRetCode) ConsoleWrite($sServerResponse & @LF) Func JsonPost_Test($sJson, ByRef $iRetCode) ; Init Easy Curl Interface e set url (echo service) Local $oCurl = Curl_Easy_Init() curl_easy_setopt($oCurl, $CURLOPT_URL, "https://httpbin.org/post") ; Set content type header Local $headers = curl_slist_append(0, "Content-Type: application/json") curl_easy_setopt($oCurl, $CURLOPT_HTTPHEADER, $headers) ; Post fields & size curl_easy_setopt($oCurl, $CURLOPT_POSTFIELDS, $sJson) curl_easy_setopt($oCurl, $CURLOPT_POSTFIELDSIZE, StringLen($sJson)) ; Set callbac function to get server response back (see global var $_cURL_OutputBuffer) $hWriteFunc = DllCallbackRegister("WriteFunc_CallBack", "uint:cdecl", "ptr;uint;uint;ptr") curl_easy_setopt($oCurl, $CURLOPT_WRITEFUNCTION, DllCallbackGetPtr($hWriteFunc)) ; Ignore ssl certificates check curl_easy_setopt($oCurl, $CURLOPT_SSL_VERIFYPEER, 0) curl_easy_setopt($oCurl, $CURLOPT_SSL_VERIFYHOST, 0) ; Execute the post request $iRetCode = curl_easy_perform($oCurl) ; Set return trasfer & clear output buffer global var Local $sReturnTransfer = $_cURL_OutputBuffer $_cURL_OutputBuffer = "" Return SetError(0, 0, $sReturnTransfer) EndFunc Func WriteFunc_CallBack($ptr,$nSize,$nMemb,$pStream) Local $vData = DllStructCreate ("byte[" & $nSize*$nMemb & "]",$ptr) $_cURL_OutputBuffer &= BinaryToString(DllStructGetData($vData,1)) Return $nSize*$nMemb EndFunc  
      curlJsonPost.zip
    • By D2thunder
      Hi all, I wasnt active in this Forum forum for Years. 😅
      Since I need something with Json in AutoIt i write a little UDF to save a variable to file to read it with another language - and back. After a while until my other script grows i thought - lets integrate all variables wich is possible, because i want have arrays to.
      This is my first public UDF in Autoit - normaly my AutoIt scripts are quick an dirty.... - like the examples for this udf. - someone want to write nice examples?
      I tried to write this UDF properly, cared for processing speed, low mem consumption as possible, a short code, and a high usability without beeing very familiar with arrays.
      What is it for? - convert nearly all types of variables to a json string for saving it in a file or to an ini. Read it back in to a same formated variable and preserv variable types. All array types are supported with nested arrays, the only restriction is ram and array/stringsize - and time if the array is very big. You can use Filters for variable types and some other options.
      If anyone found a bug or any suggestions, please post it.
       
      get Json.au3 from here Json.au3
       
       
      JsonVar 2019.01.25.1.zip
    • By JoeBar
      Hi, i'm trying to implement Imgur API functions in an AutoIt program.
      I successfully coded the oAuth2 Authentication and i'm testing some Imgur functions.
       
      Example : https://api.imgur.com/3/account/me/images
      The string received is like :
      {"data":[{"id":"fd6f54s","title":null,"description":null,"datetime":1574502473,"type":"image\/png","animated":false,"width":1147,"height":715,"size":53516,"views":18,"bandwidth":963288,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":"ACCOUNT","account_id":ACCOUNTID,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"d6f5sd4fsf","name":"image","link":"https:\/\/i.imgur.com\/fd6f54s.png"} I'm using JSON.au3 UDF and i don't manage to make it working :
      Local $Obj = Json_Decode($hRequestSSL) Local $Links = Json_Get($Obj, '["data"]["link"]') The Json_Decode sends in console :
      "E:\Portable\Dev\AutoIt3\IncludeP\JSON.au3" (374) : ==> Variable must be of type "Object".: Return $Object.Keys() Return $Object^ ERROR It says it's not an object or i have seen in some UDF that Json_Decode takes a string as parameter.
      I don't know what's wrong.
×
×
  • Create New...