0

I am trying to add an object in an array to an item in a JSON object.

The result I am looking for is:

{ "AvailableFacets":[ "color", "sheenlevel" ], 
  "Selections":[ 
      { "Facet":"color", "Value":"red" }, 
      { "Facet":"color", "Value":"blue" } 
  ]
}

but I get the error "TypeError: myJsonObject.Selection.push is not a function" when doing the following:

var testJson = function () {
    var myJsonObject = $.parseJSON('{"AvailableFacets":["color", "sheenlevel"]}');
    myJsonObject.Selection = "[]";
    var newObject1 = $.parseJSON('{"Facet":"color", "Value":"red"}');
    var newObject2 = $.parseJSON('{"Facet":"color", "Value":"blue"}');
    myJsonObject.Selection.push(newObject1);

    return myJsonObject;
};

What am I doing wrong?

5
  • Why are you setting Selection to a string instead of an array? Commented Mar 26, 2013 at 0:49
  • myJsonObject.Selection = [];, but since you're testing JSON: myJsonObject.Selection = $.parseJSON('[]'); :p Commented Mar 26, 2013 at 0:51
  • Am I setting it to a string? I am new to this, thought that was an array. Commented Mar 26, 2013 at 0:51
  • 1
    "[]" is a string containing the two characters [ and ], while [] is an array literal containing zero items. Commented Mar 26, 2013 at 0:53
  • Got it! "[]" string, not array. Thanks :) Commented Mar 26, 2013 at 0:58

1 Answer 1

2

"[]" !== []. Did that help? You are using the wrong types. Also you are looking for an output with "Selections" but you are attempting to define "Selection", but I assume that is a typo. This should work:

myJsonObject.Selection = [{"Facet":"color", "Value":"red"},{"Facet":"color", "Value":"blue"}];

But if you wanted to parse a string of JSON as JSON then just change

myJsonObject.Selection = "[]";

to:

myJsonObject.Selection = [];
Sign up to request clarification or add additional context in comments.

5 Comments

You guys are beautiful! Both [] and $.parseJSON('[]') worked!
Thanks for pointing out the typo as well, had not seen that. :)
Do I need to use $.parseJSON all of those times, or is it overkill?
It's overkill. You should only use parseJSON when you are parsing a string (like from an AJAX request, or a textBox)
I kept the first $.parseJSON only, works fine without the rest. Thank you all very much, it's wonderful to get such quick replies, especially since it's two in the morning here in Sweden :S

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.