user2733659 user2733659 - 6 months ago 11
JSON Question

JSON Parse [ and ]

I have JSON data from URL and I need split values,

"name":"michael",
"number":"0015454545",
"age":"22",
"interest":[
["swim","baseball","music","tenis"],
["washington","3","27","a"],
["New york","2","16","b"],
["los angeles","21","11","c"],
["dallas","7","22","a"]
]


My code:

Dim json As String = MyjsonDataLink
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList

For Each item As JProperty In data
item.CreateReader()
If item.Name = "interest" Then
Response.Write(item.Value.ToString)
Response.Write("<br><br><br>")
Next
End If
Next


But, text output is,

["washington","3","27","a"],
["new york","2","16","b"],
["los angeles","21","11","c"],
["dallas","7","22","a"]]


How do I extract the "washington", "new york", "los angeles", and "dallas" strings?

Answer

LINQ was built for situations like this. Here's a console app illustrating:

Imports Newtonsoft.Json.Linq
Module Module1
  Sub Main()
    'ignore the <a> tag, it's just a trick for multi-line strings
    Dim json = <a>
{"name":"michael",
"number":"0015454545",
"age":"22",
"interest":[
    ["swim","baseball","music","tenis"],
    ["washington","3","27","a"],
    ["New york","2","16","b"],
    ["los angeles","21","11","c"],
    ["dallas","7","22","a"]
]}</a>.Value
    Dim ser As JObject = JObject.Parse(json)
    'now let LINQ do the work for us
    Dim output = From s In ser("interest").Children Select s.First
    For Each item In output
      Console.Write(item)
      Console.Write("<br/><br/><br/>")
    Next
    Console.ReadLine()
  End Sub
End Module

Result:

swim<br/><br/><br/>washington<br/><br/><br/>New york<br/><br/><br/>los angeles<br/><br/><br/>dallas<br/><br/><br/>
Comments