I have an array of object which i want to convert to a JSON
string but i recieve the following error: JavaScript exception :Uncaught TypeError: Converting circular structure to JSON
From what i understand this is because there is a loop in references. i've searched here on SO for solutions and someone came up with a 'replace function'. this looked something like this:
var cache = [];
JSON.stringify(o, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache = null; // Enable garbage collection
but using this gives me the following error: Maximum call stack size exceeded
.
i think this solution doesn't really fits my needs, because i am not intrested in all the elements ofthe array that i'm trying to convert. These elements are added are 3rd party(google maps) so i have no influence on their child objects.
This is a screenshot of my array object:
i am only interested in the following items:
Tour
-id
-name
-days :
-id
-name
-markers :
-dayId
-title
-position :
-nb
-ob
-thumbs :
- 0
- 1
- ...
because the object array is created by several functions/services/factories is it difficult to make a fiddle or provide some code samples.
Any sugestion how to convert an array like this to JSON is welcome, thanks in advance
For anyone interested, i ended up making my own array with just the elements that i needed:
function CreateJson(tour){
var sJson = {};
sJson.name = tour.name;
sJson.id = tour.id;
sJson.days = [];
sJson.markers = [];
sJson.thumbs = [];
for(i = 0; i < tour.days.length; i++){
sJson.days.push({
id: tour.days[i].id,
name: tour.days[i].name
});
for(j = 0; j < tour.days[i].markers.length; j++){
sJson.markers.push({
id: tour.days[i].markers[j].id,
dayId: tour.days[i].markers[j].dayId,
name: tour.days[i].markers[j].title
});
}
for(k = 0; k < $scope.thumbs.length; k++){
sJson.thumbs.push($scope.thumbs[k])
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.