Firebase multi-path update “invalid data; couldn't parse JSON object, array, or value”

不想你离开。 提交于 2020-01-03 02:40:27

问题


I was excited when Firebase announced multi-path updates a while back. I have a fairly complex data structure that requires writes to several locations for managing relationships between entities, so multi-path updates came at the perfect time - I didn't have to worry about making several back-to-back writes/updates (and risk having Firebase rate-limit me).

So, I coded everything up, buckled in, and performed a multi-path update (using the Rest API), only to be let down by the following response:

"error" : "Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names."

I looked at the docs to see if I was using invalid characters (., $, #, [, ], /) in any key names. I wasn't (other than the forward-slash becuase this was the super new and awesome multi-path update that allowed for such a character in the key).

I quickly opened up the Javascript console in Chrome, ran JSON.parse() on my string, and it parsed into a valid table, so what's the problem?

My update contained the following:

{
  "foo/bar": {
    "data": {
      "baz": 1
    }
  },

  "foo/bar/data": {
    "quu": 2
  }
}

回答1:


After an unsuccessful attempt at using the official support@firebase.com channel, I took to brute force debugging.

I parsed out each key/value pair separately as its own table and attempted a multi-path update, and each time it worked. This is when I knew I was onto something odd. Then I slowly built up the entire table key by key until the multi-path update failed and I saw the issue.

My update contained the following:

{
  "foo/bar": {
    "data": {
      "baz": 1
    }
  },

  "foo/bar/data": {
    "quu": 2
  }
}

And I was hoping for the resulting data in Firebase:

{
  foo: {
    bar: {
      data: {
        baz: 1,
        quu: 2
      }
    }
  }
}

So, the simple answer is, a multi-path update cannot contain two key names that write to the same location (or a location deeper in the same path).

Now, my multi-path update contained upwards of 20 key/value pairs, so it wasn't quite as easy to spot as the example I've laid out here, so cut me a little slack. I can understand for a number of reasons why this may not be allowed (the atomicity of the request, which update gets applied first, etc), but my issue is that the error returned from Firebase was not only not helpful, it flat out pointed me in the wrong direction, making debugging even harder.

So, the answer is to combine the two multi-path update keys that write to the same location in Firebase to look like the following:

{
  "foo/bar/data" : {
    "baz": 1,
    "quu": 2
  }
}


来源:https://stackoverflow.com/questions/36624969/firebase-multi-path-update-invalid-data-couldnt-parse-json-object-array-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!