-1

var result = "";
result += "[";
for(i=0;i<=10;i++)
  {
    result += "{ 'key': 'keyvalue" + i + "', 'values': [";
    for(j=0;j<=10;j++)
      {
        result += "{ 'key': 'subkeyvalue"+j+"', 'value':"+j+"}, ";
      }
    result += "]}, ";
  }

result += "]";

console.log(result);
console.log(JSON.stringify(result));
console.log(JSON.parse(result));

If i try to convert String to JSON.parse. I am getting below error.

JSON.parse: expected property name or '}' at line 1 column 4 of the JSON data

can you please any one resolve this problem.

G Boomanikandan
  • 124
  • 2
  • 12

4 Answers4

1

In this snippet ( result += "]}, ";) , "," (comma) is getting appended at the last, so the json will be like "},]" where you will be expecting like "}]"

itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29
0

I think you can use JSON.stringify() or use key and value in (') quote

var result = "";
result += "[";
for(i=0;i<=10;i++)
  {
    result += "{ 'key': 'keyvalue" + i + "', 'values': [";
    for(j=0;j<=10;j++)
      {
        result += "{ 'key': 'subkeyvalue"+j+"', 'value':"+j+"}, ";
      }
    result += "]}, ";
  }

result += "]";

console.log(result);

console.log(JSON.stringify(result));
itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29
0

Try to use the code given below. You should not append the , (Comma) to the last element while iterating

var result = "";
result += "[";
for(i=0;i<=10;i++)
  {
    result += '{ "key": "keyvalue' + i + '", "values": [';
    for(j=0;j<=10;j++)
      {
        result += '{ "key": "subkeyvalue'+j+'", "value":'+j+'}';
        if(j!=10) {
          result += ','
        }
      }
    result += ']} ';
    if(i!=10) {
     result += ','
    }
  }

result += ']';

console.log(result);

console.log(JSON.parse(result));
Amrinder
  • 69
  • 6
0

Don't create JSON strings manually through string concatenation. Just...don't.

Create an array, create appropriate objects and add them to the array, then pass the array to your charting library as is.

Or if you actually need a JSON string use JSON.stringify() on the array.

And note that there is no such thing as a "JSON object".

var result = [];
var vals;
for(var i=0;i<=10;i++) {
  vals = [];
  for(j=0;j<=10;j++) {
    vals.push( { key: 'subkeyvalue'+j, value: j } );
  }
  result.push( { key: 'keyvalue' + i, values: vals } );
}

// someChartFunction(result);

console.log(result);
console.log(JSON.stringify(result));
nnnnnn
  • 147,572
  • 30
  • 200
  • 241