Javascript Data Type How to - Output result as JSON String








Question

We would like to know how to output result as JSON String.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from   w ww  .j  av  a 2 s  .c  o m-->
array1 = [5, 1, 3];
array2 = {1: 15, 2: 20, 3: 10, 4: 5, 5: 50};
var result = {};
for (var i in array2) {
    if (array1.indexOf(+i) < 0) {
        result[i] = array2[i];
    }
}
document.writeln(JSON.stringify(result));

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: