15

I am trying to stringify a javascript object, however when I do this a get the following error:

TypeError: cyclic object value

I don't believe that my code contains any cyclic references (newServiceObject is not referenced inside the object), so I do not understand why I am getting this message.

I want to turn my object that contains two properties and an array into a single string.

var serviceName = $('#newServiceNameBox').val();
        var serviceCodeElemList = $(".ServiceCodeName").map(function() { return $(this).html(); } );
        //create the new service object
        var newServiceObject = {ServiceId:-1, ServiceName: serviceName, ServiceCodes: serviceCodeElemList };

        var appendNewService = '&newService='+JSON.stringify(newServiceObject);

The error occurs on the last line (the JSON.Stringify() ) but I have no idea why!

1
  • can you post the JSON data in newServiceObject object ? Commented Sep 1, 2015 at 14:48

2 Answers 2

9

This is typically because you are trying to serialize a JavaScript object that has properties that point to each other in a cycle.

In your example, newServiceObject.serviceCodeElemList points to a jQuery object which does have cycles in it: Its context property which points to a document object. A document object has pointers to DOM elements that have pointers back to the document through the ownerDocument property

    var jqueryObj = $('div');
    console.log(jqueryObj.context); // Document object
    console.log(jqueryObj.context.body.firstChild.ownerDocument); // Document object
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

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

2 Comments

see answer above! As per my question, I couldn't see anything obvious like this in my code. My guess is that something internal to the jquery object does this
@NeilP I've modified the answer to explain where the cycle is in jQuery objects.
3

My problem was that when using jquery to build the array, I should have included the toArray() method after the map function.

var list = $(".ServiceCodeName").map(function() { return $(this).html(); } ).toArray();

Therefore when the array is included in the object, it is a standard array and not a jquery object.

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.