aCarella
aCarella

Reputation: 2578

Accessing JSON Information: Objects in Objects

I have a JSON object that has a JSON object inside of it. It looks as follows:

{ 
  "skuInformation": {
     "hidden": "No",
     "description": "Glass Zipper Bags",
     "velocityClass": "Fast Mover",
     "currentCatalog": "Yes",
     "discontinued": "No",
     "sku": "1861900" 
  }
}

I need the access to the individual information inside of this object through JavaScript, but I'm having trouble trying to access it.

I have a function that parses this JSON object and is returned as jsonResponse. Let's say I needed sku description. I've tried console.log with jsonResponse.description, jsonResponse[0].description, and Object.keys(jsonResponse)[0].description. None of those work, all returning undefined. How do I gain access to the key-values inside of the JSON object?

Upvotes: 0

Views: 52

Answers (2)

Ben Aston
Ben Aston

Reputation: 55729

JSON.parse(json)['skuInformation']['description'];

JSON is a text format.

JavaScript objects are JavaScript objects (and not JSON).

Upvotes: 1

TimoStaudinger
TimoStaudinger

Reputation: 42460

Once you have parsed your JSON string into a JavaScript object, you can access nested objects using the . syntax:

var jsonResponse = {"skuInformation":{"hidden":"No","description":"Glass Zipper Bags","velocityClass":"Fast Mover","currentCatalog":"Yes","discontinued":"No","sku":"1861900"}};

var description = jsonResponse.skuInformation.description;
console.log(description); // Glass Zipper Bags

As an alternative, you can also access it using the bracket syntax [] with the key as a string:

var key = 'skuInformation';
var description = jsonResponse[key].description;

More about working with objects from MDN.

Upvotes: 2

Related Questions