I need help converting this json string to a javascript array.
I've tried things like this:
var cityState = $.map(source, function (value) { return value; });
where "source" is the result of this ajax call:
$.ajax({
url: 'http://localhost:49858/Default.aspx/getstuff',
dataType: 'json',
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8"
}).done(function (source) { ...
but it's just not working correctly.
{"query": "Unit","suggestions":[{"value":"FAIRFIELD, CONNECTICUT","data":"FAIRFIELD, CONNECTICUT"},{"value":"LONG BEACH, CALIFORNIA","data":"LONG BEACH, CALIFORNIA"},{"value":"NEW YORK, NEW YORK","data":"NEW YORK, NEW YORK"},{"value":"HONOLULU, HAWAII","data":"HONOLULU, HAWAII"},{"value":"KANSAS CITY, MISSOURI","data":"KANSAS CITY, MISSOURI"},{"value":"SAN JOSE, CALIFORNIA","data":"SAN JOSE, CALIFORNIA"},{"value":"SOUTH LAKE TAHOE, CALIFORNIA","data":"SOUTH LAKE TAHOE, CALIFORNIA"},{"value":"LAKE DALLAS, TEXAS","data":"LAKE DALLAS, TEXAS"},{"value":"BROOMFIELD, COLORADO","data":"BROOMFIELD, COLORADO"},{"value":"BROOMFIELD, COLORADO","data":"BROOMFIELD, COLORADO"}]}
Screenshot of console.log(source) shows: enter image description here
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
asked Feb 28, 2013 at 20:41
Induster
7331 gold badge6 silver badges15 bronze badges
1 Answer 1
This is a strange object you get. It looks like you encoded some object as JSON, set it as value of the property of an object, and then encoded it again.
If you want to get an array of all value of your suggestions array, then you may do
var values = $.map(JSON.parse(source.d).suggestions, function(v){ return v.value });
answered Feb 28, 2013 at 20:44
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Induster
alert(source); tells me it's an [object]. but alert(source.suggestions); just breaks things. I'm confused on how to reference "suggestions". perhaps I need to cast "source" to a specific type?
Denys Séguret
To know what's in your object do
for (var key in source) console.log(key, source[key]) and look at the console.Induster
Thanks - the console shows it prepends a "d" to the front. d {"query": "Unit",...
Denys Séguret
That's strange : that can't be a valid object. Can you screenshot what you get when you do
console.log(source) ?Denys Séguret
In fact that's the opposite : you have to parse
source.d from a JSON string into a javascript object. |
lang-js
sourceis not a json-type string; it's an Object