extracting data from json string

I am new to using javascript as well as json. I need to extract certain sections from json for processing the data.

{
  "status": "SUCCESS",
  "status_message": "blah blah blah",
  "pri_tag": [
      {
          "tag_id": 1,
          "name": "Tag1"
      },
      {
          "tag_id": 2,
          "name": "Tag2"
      },
      {
          "tag_id": 3,
          "name": "Tag3"
      },
      {
          "tag_id": 4,
          "name": "Tag4"
      }
  ]
}

From the above json message I need to extract pri_tag section so that the extracted json should look like below:

[
  {name:'Tag1', tag_id:1},
  {name:'Tag2', tag_id:2},
  {name:'Tag3', tag_id:3},
  {name:'Tag4', tag_id:4},
  {name:'Tag5', tag_id:5},
  {name:'Tag6', tag_id:6}
];

How to get this done using javascript? Please help me. Thanks in advance.

Thanks friends. I was able to get this working. Thanks once again.

Answers:

Answer

try this:

  var data={
  "status": "SUCCESS",
  "status_message": "blah blah blah",
  "pri_tag": [
  {
      "tag_id": 1,
      "name": "Tag1"
  },
  {
      "tag_id": 2,
      "name": "Tag2"
  },
  {
      "tag_id": 3,
      "name": "Tag3"
  },
  {
      "tag_id": 4,
      "name": "Tag4"
  }
  ]
  };

if you get the data from Ajax request you need to parse it like this:

  var newData=JSON.parse(data).pri_tag;

if not, you don't need to parse that:

  var newData=data.pri_tag;
Answer
var data={
  "status": "SUCCESS",
  "status_message": "blah blah blah",
  "pri_tag": [
      {
          "tag_id": 1,
          "name": "Tag1"
      },
      {
          "tag_id": 2,
          "name": "Tag2"
      },
      {
          "tag_id": 3,
          "name": "Tag3"
      },
      {
          "tag_id": 4,
          "name": "Tag4"
      }
  ]
}

use this code

var result=data.pri_tag;
for(var i in result)
{
    console.log(result[i]);
}
Answer

Try this

var foo = '{"status": "SUCCESS","pri_tag": [...]}'
var bar = JSON.parse(foo)
bar.pri_tag
Answer

Assuming you have a data variable containing the JSON object, result would hold what you expect (without using the same data variable):

var result = [];

for(var i = 0; i < data.pri_tag.length; i++){
    result.push({'name': data.pri_tag[i].name, 'tag_id': data.pri_tag[i].tag_id});
}

console.log(result);

Here you are a working example.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.