0

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?

7
  • 6
    You need to use it like this jsonResponse.skuInformation.description Commented Jul 7, 2016 at 16:33
  • The one you missed was console.log(jsonResponse) ;) Commented Jul 7, 2016 at 16:34
  • Gerardo Furtado is right. It's not a valid json. Commented Jul 7, 2016 at 16:35
  • Can someone please clarify why this is not valid json. I test it using jsonlint and it showed valid Commented Jul 7, 2016 at 16:37
  • It's a valid JS object, but JSON is a collection of objects with string keys and multi-type values. ex. [{"foo": "bar", "boo": 1, "far": {"nested": 3}}] Commented Jul 7, 2016 at 16:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

JSON is a text format.

JavaScript objects are JavaScript objects (and not JSON).

1 Comment

You can remove the wrapping parentheses and use dots

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.