Beginner JSON question

Just starting out? Need help? Post your questions and find answers here.
firace
Addict
Addict
Posts: 946
Joined: Wed Nov 09, 2011 8:58 am

Beginner JSON question

Post by firace »

I'm somewhat struggling with the JSON commands (major understatement!)...

The below code returns the top Google result for a keyword, in JSON format.
How can I extract the URL from that JSON result?
Thanks!

Code: Select all


Procedure.s GetHTTPText(URL$, TimeOut=5000)
  Protected BufferSize = $1000, *Buffer = AllocateMemory(BufferSize)
  Protected ServerName$ = GetURLPart(URL$, #PB_URL_Site) 
  Protected ConnectionID = OpenNetworkConnection(ServerName$, 80) 
  If ConnectionID 
    SendNetworkString(ConnectionID, "GET "+URL$+" HTTP/1.0" +#LFCR$+#LFCR$) 
    Time = ElapsedMilliseconds()
    Repeat 
      Delay(10)
      Event = NetworkClientEvent(ConnectionID)
      If Event = #PB_NetworkEvent_Data
        Repeat
          Size = ReceiveNetworkData(ConnectionID, *Buffer, BufferSize)
          String$ + PeekS(*Buffer, Size, #PB_Ascii) 
        Until Not Size
        Inhalt = FindString(String$, #LFCR$, 1)
        If Inhalt
          String$ = Mid(String$, Inhalt+3)
        EndIf
      EndIf   
    Until ElapsedMilliseconds()-Time > TimeOut Or String$
    CloseNetworkConnection(ConnectionID)
  EndIf 
  FreeMemory(*Buffer)
  ProcedureReturn String$
EndProcedure

InitNetwork()  

  S$ = GetHTTPText("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=1&q=alcatraz" )


  Debug S$
  

    ParseJSON(1, S$)
    Debug JSONType(JSONValue(1))

Last edited by firace on Sat Jun 27, 2015 3:16 pm, edited 2 times in total.
freak
PureBasic Team
PureBasic Team
Posts: 5940
Joined: Fri Apr 25, 2003 5:21 pm
Location: Germany

Re: Beginner JSON question

Post by freak »

The JSON commands let you walk the nested JSON data to get to individual values. For example like this:

Code: Select all

ParseJSON(1, S$)
response = JSONValue(1)
responseData = GetJSONMember(response, "responseData")
results = GetJSONMember(responseData, "results")
result = GetJSONElement(results, 0)
url = GetJSONMember(result, "url")
Debug GetJSONString(url)
However, as you can see this can become cumbersome. If you know that the JSON will be of the same structure every time (as it is with such web APIs), i find it easier to map the results directly into PB structures and work with that.

Basically you define nested structures to match the JSON data like this:
  • JSON Arrays (with "[]") can be mapped to a PB Array or List
  • JSON Objects (with "{}") can be mapped to either a PB Map or a sub-structure.
  • Everything else can be mapped to a single value of appropriate type
Once this is done, you can use ExtractJSONStructure() to read the entire JSON data into the structure.

Example:

Code: Select all

Structure SearchResult
  GsearchResultClass.s
  unescapedUrl.s
  url.s
  visibleUrl.s
  cacheUrl.s
  title.s
  titleNoFormatting.s
  content.s
EndStructure 

Structure CursorPage
  start.s
  label.i
EndStructure

Structure SearchCursor
  resultCount.s
  Array pages.CursorPage(1)
  estimatedResultCount.s
  currentPageIndex.i
  moreResultsUrl.s
  searchResultTime.s
EndStructure

Structure ResponseData
  Array results.SearchResult(1)
  cursor.SearchCursor
EndStructure

Structure Response
  responseData.ResponseData
  responseDetails.s
  responseStatus.i
EndStructure

ParseJSON(1, S$)
ExtractJSONStructure(JSONValue(1), @response.Response, Response)

Debug response\responseStatus
Debug response\responseData\results(0)\titleNoFormatting
Debug response\responseData\results(0)\url
quidquid Latine dictum sit altum videtur
User avatar
falsam
Enthusiast
Enthusiast
Posts: 632
Joined: Wed Sep 21, 2011 9:11 am
Location: France
Contact:

Re: Beginner JSON question

Post by falsam »

Thank freak, very good demonstration :)

I often use ComposeJSON() to review the content of JSON.

Example: Debug ComposeJSON(1, #PB_JSON_PrettyPrint)

➽ Windows 11 64-bit - PB 6.21 x64 - AMD Ryzen 7 - NVIDIA GeForce GTX 1650 Ti

Sorry for my bad english and the Dunning–Kruger effect 🤪
firace
Addict
Addict
Posts: 946
Joined: Wed Nov 09, 2011 8:58 am

Re: Beginner JSON question

Post by firace »

Thank you so much freak, that was most helpful!
destiny
User
User
Posts: 29
Joined: Wed Jul 15, 2015 12:58 pm
Location: CCCP

Re: Beginner JSON question

Post by destiny »

freak, very useful if json data has the same structure every time!
Post Reply