pgtips
pgtips

Reputation: 1338

How to manipulate this JSON using Javascript

I am getting this response from an API:

{
  "statuses": {
    "status": [
      {
        "name": "Member", 
        "id": "1"
      }, 
      {
        "name": "Attender", 
        "id": "3"
      }, 
      {
        "name": "Child", 
        "id": "4"
      }
    ]
  }
}

But I need to somehow flatten the response to be this:

{
  "name": "Member", 
  "id": "1"
}, 
{
  "name": "Attender", 
  "id": "3"
}, 
{
  "name": "Child", 
  "id": "4"
}

How can I do that using Javascript?

Upvotes: 0

Views: 41

Answers (3)

tinlinnsoe
tinlinnsoe

Reputation: 173

In fact, you just need to retrieve by response.statuses.status from your Javascript object.

But , If you needed to convert json to javascript object,
please use JSON.parse(your json response) method using JSON.js.

Download the JSON.js from https://github.com/douglascrockford/JSON-js

Upvotes: 0

seg-s
seg-s

Reputation: 55

You can do JSON.parse(str) and then you you just take the data from status[x]

If you really want to keep it as a string you can do var content = str.match(/\[(.*?)\]/);

Upvotes: 2

JGV
JGV

Reputation: 5187

var response = {
  "statuses": {
    "status": [
      {
        "name": "Member", 
        "id": "1"
      }, 
      {
        "name": "Attender", 
        "id": "3"
      }, 
      {
        "name": "Child", 
        "id": "4"
      }
    ]
  }
}

var statusObj = response.statuses.status;

$('#result').text('First name is: ' + statusObj[0].name)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label id="result"/>

Upvotes: 3

Related Questions