-1

Hi I have a snippet of a json I have to parse, I made it smaller so it's easier to see.

[
  {
    "trends": [
      {
        "name": "#CyberMonday",
        "url": "https://twitter.com"
      },
      {
        "name": "#BlackFriday",
        "url": "https://twitter.com"
      }
    ],
    "as_of": "2016-11-28T20:46:09Z",
    "created_at": "2016-11-28T20:40:17Z",
    "locations": [
      {
        "name": "Worldwide",
        "woeid": 1
      }
    ]
  }
]

How would I find the "name" for both sections under "trends". According to the JSONEditor I used online it says that trends is an array, I'm not familiar with getting jsonobjects when they're an array. Help please? I know how to do it if it weren't an array but now I'm struggling. Thanks!

Bryan
  • 11
  • 3

1 Answers1

0

you can access parameters inside an array of JSON by referring to the index number of the object as mentioned below:

var sampleJson = [
  {
    "trends": [
      {
        "name": "#CyberMonday",
        "url": "https://twitter.com"
      },
      {
        "name": "#BlackFriday",
        "url": "https://twitter.com"
      }
    ],
    "as_of": "2016-11-28T20:46:09Z",
    "created_at": "2016-11-28T20:40:17Z",
    "locations": [
      {
        "name": "Worldwide",
        "woeid": 1
      }
    ]
  }
]

/* To access the first object */
sampleJson.trends[0].name

/* To access the second object */
sampleJson.trends[1].name

Also you can run a for loop through the array and accessd properties:

for(var i=0; i < sampleJson.trends.length; i++){
    console.log(sampleJson.trends[i].name);
}