-1

I have a json string received from websocket :

{  
   "type":"newLoan",
   "cartItems":{  
      "numberOfItems":null,
      "bookList":[  
         {  
            "id":"1",
            "title":"The Count of Monte Cristo",
            "author":"Alexandre Dumas     ",
            "genre":"Comedy",
            "returnDate":"January 15"
         }
      ]
   }
}

This result is shown after console.log(receivedMessage), but when I try to access type property by console.log(receivedMessage["type"]) it gives me undefined.

Still the same with console.log(receivedMessage.type).

How could I access the type property?

Tom
  • 445
  • 1
  • 4
  • 10
user2997779
  • 297
  • 1
  • 16
  • 3
    Works fine [codepen](http://codepen.io/AlexChar/pen/NPGLmQ) – Alex Char Dec 03 '14 at 14:11
  • 3
    Is it maybe still a string instead of an object? Try `console.log(JSON.parse(receivedMessage).type)`. – MildlySerious Dec 03 '14 at 14:12
  • 1
    Please post the complete code if possible so we can be able to help you. – Rahul Desai Dec 03 '14 at 14:13
  • var obj = { "type":"newLoan", "cartItems":{ "numberOfItems":null, "bookList":[ { "id":"1", "title":"The Count of Monte Cristo", "author":"Alexandre Dumas ", "genre":"Comedy", "returnDate":"January 15" } ] } }; console.log(obj.type); works fine. – mohsinali1317 Dec 03 '14 at 14:13

2 Answers2

1

There is probably an issue with the headers that are being sent along with your string, if the content type isn't set to application/json or the javascript equivalent then it will be treated as a string and no a json object

DrRoach
  • 1,320
  • 9
  • 16
  • But still, I should be able to parse it in javascript, using JSON.parse(), no? Doing this I am getting a parsing error. – user2997779 Dec 03 '14 at 14:16
  • No. If you get a json string returned with the `text/html` content type then your javascript will completely ignore that the string is json and treat it as one long text string and that it why console logging it works but when you try and access the objects it will give `undefined` as it isn't being treated as a json object that javascript can interact with – DrRoach Dec 03 '14 at 14:18
  • If I go higher, that snippet of json is cut from a bigger json code. Would that have something to do with my error? – user2997779 Dec 03 '14 at 14:20
  • It shouldn't but if you can access some parts of the json response then it wont be your headers – DrRoach Dec 03 '14 at 14:22
0

try:

JSON.parse(receivedMessage).type
lem2802
  • 1,152
  • 7
  • 18