I am trying to use jQuery to iterate through the objects in this JSON expression:
[
{
"value": 609,
"label": "Wyandotte, MI"
},
{
"value": 3141,
"label": "Wilmington, NC"
}
]
Such that each object consists of two properties, value and label.
This is what I have so far:
$(data).each(function () {
alert('value: ' + this.value + ' label: ' + this.label);
});
But I keep getting an error: Uncaught Error: Syntax error, unrecognized expression
Can anyone help?
Edit:
The data variable in the example was arbitrary. What is actually happening is I'm getting an array of objects something like this:
data =
[
locations: "[{"value":5626,"label":"Bensenville, IL"}]",
notes: "Sample note"
]
Then I call data = JSON.parse(data);
And then I perform the iteration on data.locations, which is producing the error.
Edit (again):
https://jsfiddle.net/e2p7gdod/
I keep trying to reproduce what I'm seeing.
This is how I'm producing my return result:
public JsonResult Foo()
{
var data = new JObject();
data["locations"] = "[{'value': 609,'label': 'Wyandotte, MI'},{'value': 3141,'label': 'Wilmington, NC'}]";
data["supervisor"] = "John Doe";
data["notes"] = "Sample note";
return new JsonResult()
{
Data = JsonConvert.SerializeObject(data),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
.each()call? Where doesdataget its value?data)datain yourEditis invalid syntax. When you have keys and values, they have to be in an object, not an array. It should bedata = { locations: ..., notes: "Sample note" }JSON.parse, the value ofdatashould be a string, not an array.