Reputation: 167
Javascript JSON.parse() is unable to parse string that contains XML or SVG.
I have tried remove attributes from example and it worked like a charm, notice it only fails when XML contains attributes.
Following JSON string are failed to passed using JSON.parse();
{ "id": 1, "mahtml": "<math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><msup><mi>a</mi><mn>2</mn></msup><mo>−</mo><mn>2</mn><mrow><mo>(</mo><mi>a</mi><mo>×</mo><mi>b</mi><mo>)</mo></mrow><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></math>" }
{ "id": 1, "svg": "<svg height=\"100\" width=\"100\"><circle cx=\"50\" cy=\"50\" r=\"40\" stroke=\"black\" stroke-width=\"3\" fill=\"red\" /></svg>" }
Following JSON string are parsed successfully using JSON.parse();
{ "id": 1, "mahtml": "<math><msup><mi>a</mi><mn>2</mn></msup><mo>−</mo><mn>2</mn><mrow><mo>(</mo><mi>a</mi><mo>×</mo><mi>b</mi><mo>)</mo></mrow><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></math>" }
{ "id": 1, "svg": "<svg/><circle/></svg>" }
Upvotes: 2
Views: 579
Reputation: 22876
I am guessing the JSON is copied manually. \"
has to be \\"
for the \
to be escaped :
var json = '{ "id": 1, "mahtml": "<math xmlns=\\"http://www.w3.org/1998/Math/MathML\\" display=\\"block\\"><msup><mi>a</mi><mn>2</mn></msup><mo>−</mo><mn>2</mn><mrow><mo>(</mo><mi>a</mi><mo>×</mo><mi>b</mi><mo>)</mo></mrow><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></math>" }'
console.log( JSON.parse(json) )
Upvotes: 2