1

I have a json like

var obj={
"address":{
       "addlin1":"",
       "addlin2":""
         },
 "name":"sam",
 "score":[{"maths":"ten",
            "science":"two",
             "pass":false
           }]
}

Now when Iam trying to modify the json iam try an array variable and passing above json to that like

var data=JSON.parse(obj);
var json={}; 
json['name']=data['name'];
json['address']={};
json['address']['addressline1']=data['address']['addlin1'];
json['address']['addressline2']=data['address']['addlin2'];
json['marks']={};
json['maths']=data['score']['maths'];

For name and address I was able to form the json as i was expecting.But for marks I was unable.May be in obj json score values are in [ ]

So,when i console the json it is in this way

"name":"sam",
"address":{
   "addresslin1":"",
   "addresslin2":""
     },
  "score":{}
  }

So how can I also read the values inside [] array.

Can someone help me Thanks

2
  • youre nearly there - score is an array according to your first bit of code so access the first object in the score array and then continue as you were score[0].maths. You can use dot notation with javascript objects too, if you prefer along the lines of data.address.addlin1 Commented Oct 6, 2016 at 19:13
  • obj isn't JSON... that's at least part of your problem. Just use obj directly. Commented Oct 6, 2016 at 19:16

3 Answers 3

3
json['maths']=data['score'][0]['maths'];

if you're not sure that data['score'] has any elements you can check prior to reading maths key:

if (data['score'].length) {
    json['maths']=data['score'][0]['maths'];
}
Sign up to request clarification or add additional context in comments.

Comments

0

data['score'] is an array, so you can't read it like that

json['maths']=data['score']['maths'];

you have to read it like that:

json['maths'] = data['score'][0].maths;

Also, obj is not a JSON, but a JavaScript object. You can use it directly.

json['maths'] = obj['score'][0].maths;

A JSON is a string, like that:

JSON.stringify(obj)
var json = "{"address":{"addlin1":"","addlin2":""},"name":"sam","score":[{"maths":"ten","science":"two","pass":false}]}";

Comments

0

create another json2 to contain score data then assign to json.

for example :

        var json={}; 
        json2 = {}
        json2[0] = 1;
        json2[1] = 2;
        json[0] = json2;

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.