Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

extjs - How to avoid extra nesting in json string

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.

question from:https://stackoverflow.com/questions/65835747/how-to-avoid-extra-nesting-in-json-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"
    (...)
  }]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...