Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase REST API POST request fails with error: "Invalid data; couldn't parse JSON object, array, or value..."

I'm trying to use Firebase REST API to save stuff into my data store. I tried with jQuery and vanilla JS XHR. However, both give the same error. 403 Bad Request and this response:

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

Here is my example JSON, I'm trying to save:

{
    "date": "2pm", 
    "name": "John"
}

Here is the example ajax request:

jQuery.ajax({
    accept: "application/json",
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "https://something.firebaseio.com/endpointnode.json",
    data: {
        "name": "John", 
        "date": "2pm"        
    },
});

Response of the request:

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

As you can see, there is no special chars or anything. It should just work.

It works fine with CURL and Httpie. I tried to check -v option in Httpie for details. I put all of the headers as Httpie does. Nothing helped. By the way, my environment is writable so there should not be any permission issue.

Any idea how to achieve this?

Thanks.

like image 437
Hakan Avatar asked Jun 12 '15 10:06

Hakan


3 Answers

You have specified that your AJAX request contains json string by assigning contentType property. However, the paramaters attached to request is not JSON string. In order to make data as json string, just invoke JSON.stringify(params) method.

Following code snippet can assist you to solve the problem.

var data = {"name": "John", "date": "2pm"};
jQuery.ajax({
    accept: "application/json",
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "https://something.firebaseio.com/endpointnode.json",
    data: JSON.stringify(data),
});

Cheers.

like image 200
gokhanakkurt Avatar answered Oct 11 '22 19:10

gokhanakkurt


Your data needs to be a string, use JSON.stringify to convert your object to a string:

data: JSON.stringify({"name": "John", "date": "2pm"})
like image 43
Anthony Aerts Avatar answered Oct 11 '22 18:10

Anthony Aerts


if you want to store your value as JSON not as string check your keys. As error message says "Perhaps you're using invalid characters in your key names." characters like (/.\,) are not allowed in keys.

like image 30
shivg Avatar answered Oct 11 '22 20:10

shivg