NewPHPer NewPHPer - 3 months ago 10
JSON Question

JSON Parse JavaScript

I am trying to parse a JSON string

Here is my sample JSON string;

{ "className": "Rectangle", "data": { "x": 685, "y": 283, "width": 179, "height": 169, "strokeWidth": 5, "strokeColor": "#000", "fillColor": "rgba(224,224,224,0.28)" }, "id": "c4c49b39-d0cd-f7c7-ea89-356753051de2" }


Here is my code to parse;

var obj;
obj = JSON.parse( { "className": "Rectangle", "data": { "x": 685, "y": 283, "width": 179, "height": 169, "strokeWidth": 5, "strokeColor": "#000", "fillColor": "rgba(224,224,224,0.28)" }, "id": "c4c49b39-d0cd-f7c7-ea89-356753051de2" } );
console.log( obj.className );


Here is the error thrown

Uncaught SyntaxError: Unexpected token o in JSON at position 1


I need to access the X and Y values.

joc joc
Answer

As stated, you're trying to read an object, in javascript var obj = {} creates an object and var arr = [] creates an array.

BUT: if you MUST parse a json simply put ' in the begining and the end to tell parser IT IS a json string:

obj = JSON.parse( '{ "className": "Rectangle", "data": { "x": 685, "y": 283, "width": 179, "height": 169, "strokeWidth": 5, "strokeColor": "#000", "fillColor": "rgba(224,224,224,0.28)" }, "id": "c4c49b39-d0cd-f7c7-ea89-356753051de2" }' );

Then console.log( obj.className ); will output Rectangle.

Comments