1

I'm a java developer, new to javascript and have a JSON string coming from a WebService that needs to be parsed in JavaScript

JSON String:

{
  "myArrayList": [
      {
         "myHashMap": {
               "firstName": "Clara",
               "name": "Housing and Community Development"
          }
      },
     {
         "myHashMap": {
               "firstName": "Nick",
               "name": "Housing and Community Development"
         }
     }
  ]
}

I have tried the following to parse the data but always get 'undefined'. The webservice retrieves the text as above in string format.

$.getJSON("http://localhost:7001/WS/Users?Id=35",
    function (jsonData)
    {
       for (var counter in jsonData.myArrayList) {
            alert(jsonData.myArrayList[counter]['name'])
       }
   });

However the alert always displays 'undefined'. Any help on resolving this would be highly appreciated. Thanks.

2
  • 2
    You seem to be overlooking the myHashMap property. Also for...in is problematic with arrays if the order matters. You’re better off with forEach or for...of. Commented Feb 7, 2019 at 19:25
  • 1
    Thanks @MarkMeyer. alert((jsonData.myArrayList[counter]['myHashMap']).firstName); worked. Commented Feb 7, 2019 at 19:33

4 Answers 4

1

you can acces it by arraylist[i].[harshmap] where this line can be put inside a loop and it will get all the values iteratively.

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

2 Comments

Is there a way I can get the data in the order it was inserted?
yup, use myArrayList[i].[myHarshship].[firstName],myArrayList[i].[myHarshship].[name]
1

This example destructures the object and maps the resulting array

        var dta = 
        {
          "myArrayList": [
              {
          "myHashMap": {
            "firstName": "Clara",
            "name": "Housing and Community Development"
                  }
              },
             {
           "myHashMap": {
           "firstName": "Nick",
            "name": "Housing and Community Development"
                 }
             }
          ]
        }
       const { myArrayList } = dta
       function parse() {
        myArrayList.map(list => {
       alert(list.myHashMap.name)
    })
    }
    parse()

Comments

1

JSON.parse should help you with the deserialization:

var obj = JSON.parse('[{"name":"John", "age":30, "city":"New York"}]');

obj[0].name should help you get the name.

Comments

0

The below snipped worked:

(jsonData.myArrayList[counter]['myHashMap']).firstName;

Thanks.

Comments

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.