0

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.

neelsg
  • 4,802
  • 5
  • 34
  • 58
NewPHPer
  • 238
  • 6
  • 22
  • 4
    You are trying to parse an object not a string ..... `var obj = { "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 );` ..or..... `var 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 );` – Pranav C Balan Sep 01 '16 at 09:33

2 Answers2

2

You can directly access value of x and y

var arr = { "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" };
var x = arr.data.x;
var y=  arr.data.y
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
1

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.

joc
  • 1,336
  • 12
  • 31