简体   繁体   中英

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'

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);
var myObj = $.parseJSON(result);
myObj.IsValid

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

Sure:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM