Search code examples
jsonfirefox-addon-sdk

Running firefox addon fails with Syntax Error when JSON is escaped in package.json


I'm making a firefox addon (SDK/Jetpack), and am using the Simple-Prefs module. I want to have an array in one of my preferences, so in my package.json I have written it as

{
  [...]
  "preferences":[
  [...]
  {
    "name":"audio-priority",
    "title":"Audio Priority",
    "type":"string",
    "value":"[\"audio-notifications\",\"audio-error\",\"audio-messages\",\"audio-youtube\",\"audio-twitch\"]",
    "hidden":true
  },
  [...]
}

But when I run it, it builds and the browser opens, but in the console it comes up with

console.error: ltt-notifier: 
  Message: SyntaxError: missing ) after argument list
  Stack:
    evaluate@resource://gre/modules/XPIProvider.jsm -> jar:file:///tmp/tmpn5QUOo.mozrunner/extensions/[email protected]!/bootstrap.js -> resource://gre/modules/commonjs/toolkit/loader.js:223
setDefaultPrefs@resource://gre/modules/XPIProvider.jsm -> jar:file:///tmp/tmpn5QUOo.mozrunner/extensions/[email protected]!/bootstrap.js -> resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/commonjs/sdk/addon/runner.js:66

And a whole load more stuff afterwards (stack), and the addon is not running. If I change the array to anything that does not have the \" (or any escaped characters - I tried using \u0022 instead) in, it works fine, which makes me think it could be a Mozilla Bug, but it is probably my fault.


Solution

  • Based on links from https://bugzilla.mozilla.org/show_bug.cgi?id=501156 (which links to https://groups.yahoo.com/neo/groups/json/conversations/topics/1286 ) I have figured out that the answer is that it should be

    "[\\\"audio-notifications\\\",\\\"audio-error\\\",\\\"audio-messages\\\",\\\"audio-youtube\\\",\\\"audio-twitch\\\"]",
    

    because the first time the JSON is decoded it unescapes the \" to ", but JSON requires it to still be \". By escaping the \ as well as the ", the first time it is parsed, when the entire file gets processed, it turns into

    [\"audio-notifications\",\"audio-error\",\"audio-messages\",\"audio-youtube\",\"audio-twitch\"]
    

    Which no longer closes the quotes (which I presume was an issue because the error related to an evaluate command in the native code), and means it will still be valid JSON when it comes to be decoded.