Marian07 Marian07 - 3 months ago 10
JSON Question

Firebase - JSON sent object results escaped

When I

.set(jsonObject)
into Firebase DB, using angularfire2, the object is escaped(backslashes are added before each double quote).

When I manually add the
jsonObject
into DB(console.firebase.google.com) everything works fine.



let obj = {
key0 : 0,
key1 : 1
};
console.log(obj);

let jsonObject = JSON.stringify(obj);
console.log(jsonObject);





// af is AngularFire instance
af.database.object("/myList/0").set(jsonObject)


The result in Firebase DB Console is:
"{\"key0\":0,\"key1\":1}"


But I get the expected result when I go to Firebase DB Console and replace the escaped object with the values from
console.log(jsonObject)
.

What is the problem?

Thank you

Answer

If you are setting the value this way:

let obj = {
  key0 : 0,
  key1 : 1
};
let jsonObject = JSON.stringify(obj);
af.database.object("/myList/0").set(jsonObject);

The value at /myList/0 will be a string:

{"key0":0,"key1":1}

The values shown in the console will be shown as JSON. When formatted as JSON, the above string value will be:

"{\"key0\":0,\"key1\":1}"

If you set the value using the object and not the JSON string, you should see the behaviour you are expecting:

 let obj = {
  key0 : 0,
  key1 : 1
};
af.database.object("/myList/0").set(obj);