1

I have a variable $data['tree'], that gets a row array from the database using a method, get_tree($id), from the model.

In my view's js I using

var dbTree = JSON.parse(<?php echo $tree; ?>);

When I load the page I get UncaughtSyntax Error: Unexpected token o in chrome and in firefox I get Syntax Error: Unexpected character.

So When I inspected the script element with chrome the js looked like

var dbTree = JSON.parse({"id":"2","name":"sean","userId":"51fbd3f3a8f2ba1b5b000002","accountId":"51fbd3fca8f2ba1b5b000003","createdAt":"2013-08-02 16:09:34","numRuns":null,"contactExport":"","updatedAt":"2013-08-02 20:15:14","deployed":"1","template":"0","conversation_type":"Conversation"});

I don't see anything wrong with that can some help me out.

3
  • Seems like even null must be wrapped in quotes Commented Aug 13, 2013 at 20:13
  • 7
    You're trying to parse a JavaScript object, not JSON. Just get rid of the JSON.parse() call. The error is because your object is turned into the string "[object Object]", which is seen as an array structure, but with the invalid character o as the first member. Commented Aug 13, 2013 at 20:14
  • You are right that JSON has to be parsed. But if you inject JSON in JavaScript source code, then the JSON will be interpreted as object literal, which doesn't have to and cannot be parsed. However please don't make the mistake to call object literals "JSON objects". Commented Aug 13, 2013 at 20:22

2 Answers 2

2

JSON.parse should be used with strings, not objects.

Or you even don't need to do anything. It is already an object.

Just like...

var dbTree = <?php echo $tree; ?>;
Sign up to request clarification or add additional context in comments.

Comments

2
var dbTree = {"id":"2","name":"sean","userId":"51fbd3f3a8f2ba1b5b000002","accountId":"51fbd3fca8f2ba1b5b000003","createdAt":"2013-08-02 16:09:34","numRuns":null,"contactExport":"","updatedAt":"2013-08-02 20:15:14","deployed":"1","template":"0","conversation_type":"Conversation"};
// Test it works
console.log(dbTree);

Just get rid of parse function.

1 Comment

when I do that I get an unexpected token ; and when I remove the ; I get an unexpected identifier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.