giraffeslacks
giraffeslacks

Reputation: 75

I don't understand JSON. Need some help clearing up some things

Here is what I'm working with.

jsonobject = {
  "products": [
    {
      "ProductABC-001": {
        "attributes": [
          {
            "color": "blue"
          },
          {
            "size": "large"
          }
        ]
      }
    }
  ]
};
  1. Is this a true/pure JSON object or is this considered something else?
  2. If the answer is "no" what's different from it and a pure/true JSON object?
  3. Why does the below return "undefined" instead of "Array"? From my perspective I am in the first element of the products node which means the next level is an array of attributes. This, apparently, is wrong.

jsonobject.products[0].attributes[0]

Upvotes: -1

Views: 164

Answers (2)

Guffa
Guffa

Reputation: 700910

  1. There is no JSON here at all. What you have is a Javascript object literal that is used to create a Javascript object.

  2. JSON is a text representation of data. The JSON syntax is a subset of Javascript object and array literals syntax. The object literal that you have between the = and the ; happens to follow the more strict syntax for JSON, so you could take that part of the source code and use as JSON.

  3. Because the object that you get from jsonobject.products[0] doesn't have any attributes property.

You would use jsonobject.products[0]['ProductABC-001'].attributes[0], which returns the object { "color": "blue" }


From what I can see, all that you would need is an array of product objects, that has a name and an object with attributes:

var products = [
  {
    name: "ProductABC-001",
    attributes: {
      color: "blue",
      size: "large"
    }
  }
];

Upvotes: 4

Jordan Kasper
Jordan Kasper

Reputation: 13273

1/2. No it is not, the = sign is not part of the JSON spec. You would have to remove the jsonobject = bit for that to be "pure" JSON. (You can validate any JSON here: http://jsonlint.com)

For 3, @davin-tryon is correct, you're missing the ["ProductABC-001"] bit which is where "attributes" resides. Try this:

jsonobject.products[0]["ProductABC-001"].attributes[0]

Upvotes: 0

Related Questions