0

I'm trying to convert an array of Hazards(class that i created) to JSON,

this is my code:

$.ajax({
    async: true,
    url: web + "/GetHazards",
    method: "POST",
    contentType: "application/json",
    success: function (data) {
        var res = data.d;
        var i;
        alert(res[0]);

the returned data is like this :

"[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165},{\"Hazard_ID\":3012,\"Hazard_Lat\":32.3426857

My server side code returns the correct values that i need, but the problem is when i alert the res[i] it behave like res is a string and alerts me "["

what i need to get is {\"Hazard_ID":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423}

i dont know if it mind this is my server-side code by the way:

{
    List<Returned_Hazard> rh = new List<Returned_Hazard>();
    JavaScriptSerializer json = new JavaScriptSerializer();
    .
    .
    .
    while (reader.Read())
    {
        Returned_Hazard RH = new Returned_Hazard(
            int.Parse(reader[0].ToString()),
            float.Parse(reader[1].ToString()),
            float.Parse(reader[2].ToString())
        );
        rh.Add(RH);
    }
    command.Connection.Close();
    return json.Serialize(rh);
}
3
  • data=JSON.parse(data) Commented Jun 13, 2017 at 14:41
  • JSON.parse(res) <- Will convert the JSON to JS Object Commented Jun 13, 2017 at 14:41
  • Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>), i tried Commented Jun 13, 2017 at 14:43

1 Answer 1

3

You need to parse the JSON, using JSON.parse:

var data = { d: "[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165}]"
};

var res = JSON.parse(data.d);
console.log(res[0].Hazard_ID); //3014

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

3 Comments

one moment I will try it
@كرمحاجيحيى No problem, please upvote and mark as answer if this helped.
Done, i have one more simple question, what i need to do to copy all of this data to a new array ?

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.