简体   繁体   中英

Trying to do JSON.parse but it doesnt like what i am doing with a returned string from my server

I was trying to return a string from my server which would be parsed into a javascript object. I keep getting an error though when it comes to the parsing process. I didnt know why. Maybe you know something that i do not.

My string looks like this:

{{"fname":"bob","lname":"jones"},{...}}

What i was trying to do is something like

var item = JSON.parse(myString);

It should be making item, an array of names so i could do something like:

for(var i = 0; i < item.length; i++){
    alert(item[i].fname + " " + item[i].lname);
}

Is there something i am doing wrong? The above was a sample, but below is actually code snippet:

while (reader.Read())
{
    if (reader["rt_id"] != DBNull.Value && reader["rt_name"] != DBNull.Value)
    {
          t = @"{""pValue"":""{ReportType},"+reader["rt_id"]+@""",""pText"":"""+reader["rt_name"]+@"""}";
          returnContentsArray.Add(t);
    }
}
returnContents = "{" + String.Join(",",returnContentsArray.ToArray()) + "}";
return returnContents;

On Client:

var item = JSON.parse(result); 

That string is not valid JSON. {} represents an object, which needs to have keys. It seems you want an array, use [] instead.

returnContents = "[" + String.Join(",",returnContentsArray.ToArray()) + "]";

You need to use correct JSON format. It looks like the format you should be using is

[{"fname":"bob","lname":"jones"},{...}]

Which would return an array of objects. Just make user you can validate the JSON in JSONLint of similar before trying to change up your javascript code.

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