I'm retreiving json from a webservice and iterating through the hierarchy using $.each(). The problem I have is with the "Titles", there may be a single title or multiple. How do I force the "Titles" to return an array of objects, even if there is only a single object in the collection so $.each() doesn't blow up.
'VB Webservice...
ds.DataSetName = "dsSurveys"
ds.Tables(0).TableName = "Surveys"
ds.Tables(1).TableName = "Titles"
ds.Tables(2).TableName = "Questions"
ds.Tables(3).TableName = "ResponseTypes"
Dim relSurveyTitles As New DataRelation("relSurveyTitles", ds.Tables("Surveys").Columns("SurveyId"), ds.Tables("Titles").Columns("SurveyId"))
Dim relTitlesQuestions As New DataRelation("relTitlesQuestions", ds.Tables("Titles").Columns("TitleId"), ds.Tables("Questions").Columns("TitleId"))
Dim relResponseTypesQuestions As New DataRelation("relResponseTypesQuestions", ds.Tables("ResponseTypes").Columns("ResponseTypeId"), ds.Tables("Questions").Columns("ResponseTypeId"))
relSurveyTitles.Nested = True
relTitlesQuestions.Nested = True
relResponseTypesQuestions.Nested = False
ds.Relations.Add(relSurveyTitles)
ds.Relations.Add(relTitlesQuestions)
ds.Relations.Add(relResponseTypesQuestions)
Dim doc As New XmlDocument()
doc.LoadXml(ds.GetXml())
Dim jsonText As String = JsonConvert.SerializeXmlNode(doc).Replace("null", """""").Replace("'", "'")
Return jsonText
//json response
{
"dsSurveys": {
"Surveys": {
"SurveyId": "1",
"SurveyName": "Survey 1",
"Titles": { //I would like to see this in an array (like "Questions") --> "Titles": [{
//regarless of object count
"SurveyId": "1",
"TitleId": "1",
"TitleName": "Title 1",
"Questions": [{
"SurveyId": "1",
"TitleId": "1",
"QuestionId": "1",
"Question": "Question 1?",
"isComment": "true",
"ResponseTypeId": "1"
},
{
"SurveyId": "1",
"TitleId": "1",
"QuestionId": "2",
"Question": "Question 2?",
"isComment": "true",
"ResponseTypeId": "1"
}]
}
},
"ResponseTypes": {
"ResponseTypeId": "1",
"ResponseType": "Yes|No|N/A"
}
}
}
Object.keysontitles. This returns an array of property keys present on thetitleobject. You can access the object properties by usingtitles[key].