I am trying to get two pieces of information from a JSON returned file (which is quite large). I am able to get the top level piece quite easily, namely the nearest_postcode. As you will see from the code, to retrieve the ‘ward’ I beat the file with a large stick and extract it. Can someone show or suggest how to traverse the JSON file and get to the ward_name.
https://findthatpostcode.uk/postcodes/SW1A%201AA.json
My clumsy code (which i pass a latitude and longitude to) is below:
Var results As New Dictionary
Var url As String = “https://findthatpostcode.uk/points/” + latlon + “.json”
Var ward As String
Var socket As New URLConnection
Try
// 1. Fetch the data synchronously (timeout 10s)
Var response As String = socket.SendSync(“GET”, url, 5)
Var root As New JSONItem(response)
If root.HasKey(“data”) Then
Var data As JSONItem = root.Value(“data”)
// 2. Extract Distance from attributes
If data.HasKey("attributes") Then
Var attr As JSONItem = data.Value("attributes")
results.Value("distance") = attr.Lookup("distance_from_postcode", 0.0)
End If
// 3. Extract Postcode from relationships
If data.HasKey("relationships") Then
Var rel As JSONItem = data.Value("relationships")
Var nearest As JSONItem = rel.Value("nearest_postcode")
Var postData As JSONItem = nearest.Value("data")
results.Value("postcode") = postData.Lookup("id", "Unknown")
End If
End If
Var source As String=response
Var searchfor As String=“ward_name”
// Find the starting position of your search string
Dim startPos As Integer = source.IndexOf(searchFor)
If startPos <> -1 Then
// Adjust startPos to the end of the search term if you don’t want the label included
startPos = startPos + searchFor.Length
// Find the next comma starting from our search position
Dim commaPos As Integer = source.IndexOf(startPos,",")
If commaPos <> -1 Then
// Extract between startPos and the comma
ward = source.Middle(startPos, commaPos - startPos)
Else
// No comma found, so take everything to the end of the string
ward = source.Middle(startPos)
End If
ward=ward.ReplaceAll(":","")
ward=ward.ReplaceAll(Chr(34),"")
results.Value("ward") = ward.Trim
End If
Catch e As RuntimeException
// Handle network or parsing errors
results.Value(“error”) = e.Message
End Try
app.MouseCursor=System.Cursors.StandardPointer
Return Format(results.value(“distance”),“#####.##”)+" metres from centre of "+results.value(“postcode”)+EndOfLine+ward
