Pradeep
Pradeep

Reputation: 813

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.

Upvotes: 4

Views: 45479

Answers (5)

jawn
jawn

Reputation: 1029

Hopefully this helps someone, I have a scenario where retrieving JSON.parse(someJsonObject).someAttribute doesn't work. Alternatively, you can also extract attribute data using JSON.parse(someJsonObject)['someAttribute']:

Upvotes: 0

Super Hornet
Super Hornet

Reputation: 2907

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;

Upvotes: 5

Murugan Pandian
Murugan Pandian

Reputation: 778

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]);
}

Upvotes: 1

xiaoboa
xiaoboa

Reputation: 1953

Try this

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

Upvotes: 0

jarandaf
jarandaf

Reputation: 4427

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.

Upvotes: -2

Related Questions