0

I'm having difficulty creating a JSON object through the JSON.stringify function. When I create the object manually, I can reference the correct object no problem, however, when I create the object through this function (serializeObject), it doesn't seem to recognize that it's an object. Both appear to be structured the same way.

Here's a fiddle of what I'm trying to do: http://jsfiddle.net/CyM37/1/

In this fiddle, first I'm creating the object and dumping into a div. Then I'm trying to reference one piece of the object and dump it into another div (this part isn't working). You can uncomment the code to see the hardcoded JSON object working.

JS

$('#createJSON').click(function(){
       var allItems = JSON.stringify($('#myForm').serializeObject());
       var manualJSON = { "firstName":"John","lastName":"Doe"};
        $('#results').html(allItems);
        $('#results2').html(allItems.checkbox2);
        //$('#results2').html(manualJSON.lastName);
    });


    //serialize into JSON function
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

Any ideas as to why the hardcoded JSON object is working but the one I create through a function isn't? They both appear to be structured identically.

0

2 Answers 2

2

It's because you're turning you object into a string. For example:

console.log(allItems[0]) // writes "{"

Try this:

 var allItems = $('#myForm').serializeObject();

Here's an updated code snippet:

$('#createJSON').click(function() {
  var allItems = $('#myForm').serializeObject();
  var manualJSON = {
    "firstName": "John",
    "lastName": "Doe"
  };
  $('#results').html(allItems);
  $('#results2').html(allItems["checkbox2"]);
  //$('#results2').html(manualJSON.lastName);
});


//serialize into JSON function
$.fn.serializeObject = function() {
  var o = {};
  var a = this.serializeArray();
  $.each(a, function() {
    if (o[this.name] !== undefined) {
      if (!o[this.name].push) {
        o[this.name] = [o[this.name]];
      }
      o[this.name].push(this.value || '');
    } else {
      o[this.name] = this.value || '';
    }
  });
  return o;
};
#createJSON {
  background: #ccc;
  width: 200px;
}

#createJSON:hover {
  cursor: pointer;
  color: white;
}

#results {
  border: 1px solid black;
  height: 50px;
}

#results2 {
  border: 1px solid black;
  height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='myForm'>
  <input type="checkbox" id="checkbox1" name='checkbox1' value='1 is checked' />
  <input type="checkbox" id="checkbox2" name='checkbox2' value='2 is checked' />
  <input type="checkbox" id="checkbox3" name='checkbox3' value='3 is checked' />

</form>

<div type='button' id='createJSON'>Click to create JSON object</div>
<div id='results'></div>
<div id='results2'></div>

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

Comments

0

You appear to be confused about stringify. It turns an object into a JSON string. So it doesn't make sense to try and access it's properties after you've stringify. The string doesn't have a checkbox2 property.

You serializeObject method produces an object, so use that.

Try this:

$('#createJSON').click(function(){
   var allItems = $('#myForm').serializeObject();
    $('#results').html(JSON.stringify(allItems));
    $('#results2').html(allItems.checkbox2);
});

http://jsfiddle.net/CyM37/3/

Comments

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.