I'm getting errors, in both chrome and firefox developer tools, when trying to evaluate the following:
{
"a": "",
"b": ""
}
jsonlint tells me it's valid. Putting this code in an actual javascript file and running it works fine. The strangeness shows up only when I run this in the console in chrome developer tools or firebug. What's going on here?
I'm getting errors, in both chrome and firefox developer tools, when trying to evaluate the following:
{
"a": "",
"b": ""
}
jsonlint. tells me it's valid. Putting this code in an actual javascript file and running it works fine. The strangeness shows up only when I run this in the console in chrome developer tools or firebug. What's going on here?
Share Improve this question edited May 10, 2012 at 16:14 Rob W 349k87 gold badges807 silver badges682 bronze badges asked May 10, 2012 at 16:04 morgancodesmorgancodes 25.3k39 gold badges138 silver badges191 bronze badges 2- Works for me in Firebug, or at least, it will parse it if I assign that object to a variable. I get a different error just using the object entirely on its own. – Andrew Leach Commented May 10, 2012 at 16:07
- possible duplicate of Defining a JavaScript object in console – Rob W Commented May 10, 2012 at 16:11
2 Answers
Reset to default 9You can't execute JSON in the console. The JavaScript engine thinks its a block statement, with a label.
So this:
{
"a": "", "b": ""
}
is interpreted as a block statement. The Next, the "a":
part is interpreted as a label. The "", "b"
part is interpreted as an expression (two string literals and a ma operator in-between). Now the second :
character is invalid in that position..."a"
is interpreted as a string literal, and the :
is not valid at that position.
You work with JSON like so:
- You put it in a
.json
file, - You retrieve it via Ajax as a string,
- You parse the string into an object with
JSON.parse()
.
(You can also keep JSON data as a string in a variable, for instance, or in the localStorage
object. Either way, in regard to JavaScript, JSON data should always e as a string value.)
Actually, for one-off testing (my main use of the debug console), you can enter JSON object syntax, but you have to assign it to a variable:
> var x ={
"a": "",
"b": ""
}
undefined
> x
Object
a: ""
b: ""
__proto__: Object