17

Server returns the array of object in JSON. It looks so:

{"d":"[
  {\"Id\":1,\"IsGood\":true,\"name1\":\"name1dsres\",\"Name2\":\"name2fdsfd\",\"name3\":  \"name3fdsgfd\",\"wasBorn\":\"\\/Date(284011000000)\\/\"},
  {\"Id\":2,\"IsGood\":false,\"name1\":\"fdsfds\",\"name2\":\"gfd3im543\",\"name3\":\"3543gfdgfd\",\"WasBorned\":\"\\/Date(281486800000)\\/\"}
]"}

I need to parse using JSON.parse function. I'm doing this this way:

   function myFunction(dataFromServer){
      var parsedJSON = JSON.parse(dataFromServer.d);
         for (var item in parsedJSON.d) {
          // how do I get the fields of current item?
      }

This code is not working, it returns undefined

for (var item in parsedJSON) {
      alert(item.Id);
}
  • Assuming `dataFromServer` contains the data you posted and you already parsed it, then `parsedJSON` is already an array, it does not have a property `d`. If you want to know how to access properties of objects, have a look at https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects – Felix Kling Jul 13 '12 at 10:38
  • 2
    Regarding your update: That's not how you iterate over arrays. Have a look at the following link to understand `for...in`: https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in . Use a normal `for` loop to iterate over the array. – Felix Kling Jul 13 '12 at 10:43
  • For those who come from the C# word and forget the ugly part of JS: use `for ... of` instead of `for ... in` to properly iterate over the collection. – klenium Apr 24 '22 at 20:35

5 Answers5

19

This works perfectly

    function myFunction(dataFromServer){
       var parsedJSON = JSON.parse(dataFromServer.d);
       for (var i=0;i<parsedJSON.length;i++) {
            alert(parsedJSON[i].Id);
         }
 }

But this doens't

    function myFunction(dataFromServer){
           var parsedJSON = JSON.parse(dataFromServer.d);
           for (var item in parsedJSON) {
               alert(item.Id);
         }
 }
  • 4
    And it shouldn't. The `for - in` construct is for iterating over object properties, not over array elements (like you might do in PHP or Python). JS needs an incremental for loop to iterate arrays. – Michael Berkowski Jul 15 '12 at 02:21
  • 2
    `for( index in array ){ var value = array[index]; }` – Alex Oct 18 '16 at 10:06
3

You can just access them as you would any object:

var id = item.Id;
if (item.IsGood) { ... }

If you wish to enumerate them to use somehow, have a look at this SO question.

Community
  • 1
  • 1
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
0

You can access them as you do oridinary javascript objects, that is either as item.id or item['id']

Eivind Eidheim Elseth
  • 2,294
  • 1
  • 23
  • 28
  • Inside the loop( which should be a normal for-loop, not for each) ,where you wrote your question, you get the object and just access it either by using dot notation or accessing it like a map. But as @Rab Nawas noticed the value of d isn't an array but a string of an array. This means that you have to parse it into a JSON object before accessing the elements in the array. – Eivind Eidheim Elseth Jul 13 '12 at 11:42
0
 class Program
{
    static void Main(string[] args)
    {

        var jsonString = @"{
                              ""data"": [
                                  {
                                    ""uid"": ""100001648098091"",
                                    ""first_name"": ""Payal"",
                                    ""last_name"": ""Sinha"",
                                    ""sex"": ""female"",
                                    ""pic_big_with_logo"": ""https://m.ak.fbcdn.net/external.ak/safe_image.php?d=AQAi8VLrTMB-UUEs&bust=1&url=https%3A%2F%2Fscontent-a.xx.fbcdn.net%2Fhprofile-ash2%2Fv%2Ft1.0-1%2Fs200x200%2F10018_433988026666130_85247169_n.jpg%3Foh%3Dc2774db94dff4dc9f393070c9715ef65%26oe%3D552CF366&logo&v=5&w=200&h=150"",
                                    ""username"": ""payal.sinha.505"",
                                  },
                                ]
                              }";
        dynamic userinfo = JValue.Parse(jsonString);

        IList<FacebookUserDetail> userDeatils = new List<FacebookUserDetail>();
        // 1st method
        foreach (dynamic userinfoItr in userinfo.data)
        {
            FacebookUserDetail userdetail= userinfoItr.ToObject<FacebookUserDetail>();
            userDeatils.Add(userdetail);


        }
        // 2nd Method
        var userDeatils1 = JsonConvert.DeserializeObject<FacebookUserDetails>(jsonString);
    }
}
public class FacebookUserDetail
{
    public string username { get; set; }
    //Password = EncryptionClass.Md5Hash(Guid.NewGuid().ToString()),                        
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string sex { get; set; }
    public string pic_big_with_log { get; set; }
}
enter code here
public class FacebookUserDetails
{
   public IList<FacebookUserDetail> data  { get; set; }
}
}
Mani
  • 335
  • 2
  • 10
0

You object keys and value (values if they are string) should be enclosed in double or single quotes. Else parse error will occur

const jsonArr = '[{"id": 1, "name": "Tom"}, {"id": 2, "name": "Alice"}]';

const arr = JSON.parse(jsonArr);

console.log(arr);
techloris_109
  • 547
  • 5
  • 13