Anthony
Anthony

Reputation: 536

how to access one name value pair from a JSON object

let's say i have this JSON object passed back from the server via

JavascriptSerializer oSer = new JavascriptSerializer();
string sJson = oSer.Serialize(myObject);

the json that i get returned to my client via ajax call is

"{\"IsValid\":false,\"EmployeeId\":null,\"fullName\":\"a\",\"EmailAddress\":\"n/a\",\"PhoneNumber\":\"n/a\"}"

so after $.parseJSON(result);

is it possible to retrieve just the IsValid value without looping through the whole object name/value pairs?

UPDATE: seems like when the json gets to the client the : gets changed into = between the name value pairs. so now i have to figure out how to replace the = with a : so i can parse and access it like a true object property notation.

success: function (data)
                    {
                        data.replace("=", ":");
                    }

doesn't work.

also i have the ajax dataType property set to 'json'

Upvotes: 0

Views: 743

Answers (4)

Anthony
Anthony

Reputation: 536

i found the problem. in the

  $.ajax(
        {
            type: "POST",
            data: "myJson=" + jsonData,
            url: "/myURL",
            success: function (result)
            {
               //some code
            }
         });

I had dataType: 'json' that was what was converting my correctly configured JSON from the serve

Upvotes: 0

marcosfromero
marcosfromero

Reputation: 2853

var myObj = $.parseJSON(result);
myObj.IsValid

Make sure that your result is surrounded by quotation marks, single quotes are Ok.

Upvotes: 1

Chad
Chad

Reputation: 19609

Sure:

var obj = jQuery.parseJSON(result);
alert(obj.IsValid);

Upvotes: 0

Andy E
Andy E

Reputation: 344567

You don't have to loop through each field anyway - just access it as a direct property of the result from parseJSON.

var obj = $.parseJSON(result);
alert(obj.IsValid);

Upvotes: 1

Related Questions