1

I tried to create json string according to syntax from wikipedia. I created json string with the following code:

        var data = [];
        
        data.push(
            {
                "firstName": "John",
                "lastName": "Smith",
                "isAlive": true,
                "age": 27,      
            });
            
        var addressdata = [];   

        addressdata.push(
                    {
                        "streetAddress": "21 2nd Street",
                        "city": "New York",
                        "state": "NY",
                        "postalCode": "10021-3100"
                    });
        
        data.push(
            {
                "address" : addressdata
            }
        );      

The string is correct json string. However, the json structure contains some unnecessary nesting, as shown in the Figures 1 and 2 below. More precisely, there are surplus braces for address block, and the string is also enclosured with brackets instead of braces. So, what am I doing wrong? How can I avoid this unnecessary nesting and get structure as shown in Fig. 3?

enter image description here Fig. 1

enter image description here Fig. 2

enter image description here Fig. 3

The string is generated with jsonData : data, in Ajax request.

1 Answer 1

2

You are using a list for the data variable. That's why you get brackets in the beginning and end of the JSON body. To overcome this problem you can declare the whole JSON body in the data variable like:

data = {
  "firstname": "test",
  (...)
  "address": [{
    "streetAddress": "test"
    (...)
  }]
}
Sign up to request clarification or add additional context in comments.

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.