0

I have code that calls a WCF service and returns a JSON string to the client. Below is the javascript function I am trying to use to parse the JSON but can not figure out how to traverse it.

Here is the function

loadDropDown: function(result, ddl, defaultItem) {
    var _data = result.get_object();
    //Sys.Serialization.JavaScriptSerializer.deserialize(result, true);

    this.clearDropDown(ddl);
    this.createOption(ddl, defaultItem, '');
    for (var i = 0; i < _data.length; i++) {
        var _item = _data[i];
        var _option = this.createOption(ddl, _item.Text, _item.Value);
    }
    ddl.disabled = false;
}

Here is the JSON

{
     "d": "[{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Lexus\",\"Value\":\"Lexus\"},{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Acura\",\"Value\":\"Acura\"}]"
}

any suggestions on why this is not working? Note: I am not using jquery in the solution.

3 Answers 3

1

You shouldn't be generating that json. Instead, you should be outputting

{
     "d": [{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Lexus","Value":"Lexus"},{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Acura","Value":"Acura"}]
}

(quotes removed from "d" value)

There's no reason to convert json to a string before putting it in a json object! Just put the json straight in.

Sign up to request clarification or add additional context in comments.

2 Comments

How would I get to the Text and Value properties?
@TampaRich: This all seems to come down to how WCF works. You should add that as a tag.
0

You should be able to just eval() the object (or use JSON parsing from Crockford) and access your properties in regular object notation. You may need to unescape your identifiers first, though.

Comments

0

You need to do eval(_data) before you use it as a javascript array.

for ex:

var _rawdata = result.get_object();
var _data = eval(_rawdata);
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);

this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
    var _item = _data[i];
    var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.