I was thinking that the JSON text would be easier to work with in a dictionary so I could look up the “id” value.
Didn’t realize there was an orphan JSON variable left hanging around. Thanks for pointing that out.
@David Schlam: A hint: Set JsonItem.Compact = False for better readability.
A great source to see the content of a JSONItem is http://jsonviewer.stack.hu. It gives you a tree view of any JSON pasted as text into it.
I did not realize that you could pull a value from a JSONItem the same way you could pull one from a dictionary. I thought you had to convert the JSON into a dictionary first.
I couldn’t do this command:
result(0).Value("id")
because the result is an array.
What’s interesting is that in this code:
[code]if results.IsArray then
for i as integer=0 to results.Count-1
dim nextresult as JSONItem=results.Value(i)
dim ID as integer=nextresult.value(“id”)
Break
next
end if[/code]
nextresult loads the entire JSON array on the first pass. Not sure why you need to put it in a loop.
Edit: I think I just realized why. Suppose the result pulls more than one record, then there would be more than one result.
This is a bit of code (verbose for the sake of clarity) that grabs the “id” value. In my testing (just putting this code into a button) it works with the JSON that was supplied by the original poster.
Step 1: Create a text file that contains the JSON supplied by the original poster.
{“previous”:null,“results”:[{“id”:72671236,“chart_id”:“BRCH000001” etc.
Step 2: Run the code provided below:
You open the text file that was created in Step 1.
The code will place that text in the string theJSON_String
The code will parse out the “id” that was desired.
[code]// The following code gets the JSON string sitting in a file placed inside of theJSON_String variable
// This is basically copied from the XOJO documention of TextInputStream
Dim f As FolderItem = GetOpenFolderItem(“text”) // as defined in File Type Sets Editor
Dim theJSON_String As String
If f <> Nil Then
If f.Exists Then
// Be aware that TextInputStream.Open could raise an exception
Dim t As TextInputStream
Try
t = TextInputStream.Open(f)
t.Encoding = Encodings.UTF8
theJSON_String = t.ReadAll
Catch e As IOException
MsgBox(“Error accessing file.”)
End Try
t.Close
End If
End If
// The following code takes the theJSON_String and parses it
// And retrieves the “id” contents
Dim origDict As New Xojo.Core.Dictionary
origDict = Xojo.Data.ParseJSON(theJSON_String.ToText)
Dim resultsArray( ) As Auto
resultsArray( ) = origDict.Value(“results”)
Dim resultDict As New Xojo.Core.Dictionary
resultDict = resultsArray(0)
Dim contentID_Variant As Variant
contentID_Variant = resultDict.Value(“id”)
Dim contentID_String As String
contentID_String = contentID_Variant