Error:In JSON data submission unexpected character - json

I am trying to send a push notification using onesignal.In that process i got an error
"error":"There was a problem in the JSON you submitted: unexpected character at line 1, column 1 [parse.c:652]"}
My Code is as follows:
var jsonBody = {
"app_id": "OneSignal App ID",
"include_player_ids": ["Onesignal Playerid"],
"headings": {
"en": "Sump"
},
"contents": {
"en": " Sump Level is 'Sumpper' "
}
};
var request = $.ajax({
url: "https://onesignal.com/api/v1/notifications",
headers: {
'Authorization':'Basic REST API Key',
'Content-Type':'application/json',
'Access-Control-Allow-Headers': 'SDK-Version',
'Access-Control-Allow-Origin': '*'
},
type: "POST",
data: jsonBody,
dataType: "json"
});
console.log(request);
request.success(function(msg) {
console.log("success");
});
request.error(function(jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
Can anyone help me where i am going wrong.
Thankyou.

Hi try to create an object then stringfy it to json.
var jsonBody =
{
app_id: "OneSignal App ID",
include_player_ids: [ "Onesignal Playerid", "Secondsignal Playerid"],
headings :
{
en: "Sump"
},
contents :{
en: "Sump Level is 'Sumpper' "
}
};
var request = $.ajax({
url: "https://onesignal.com/api/v1/notifications",
headers: {
'Authorization':'Basic REST API Key',
'Content-Type':'application/json',
'Access-Control-Allow-Headers': 'SDK-Version',
'Access-Control-Allow-Origin': '*'
},
type: "POST",
data: JSON.stringify(jsonBody),
dataType: "json"
});
console.log(request);
request.success(function(msg) {
console.log("success");
});
request.error(function(jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});

Related

SyntaxError: Unexpected token \n in JSON at position

I have a roblem while directing a request from Cloud Flare workers to my API. When I catch the error I get this:
SyntaxError: Unexpected token \n in JSON at position 240
when I did some research I saw some articles about it being about JSON.parse. But I couldn't find the solution.
Example Request Body:
{"link": "link", "provider": "company", "oauth": "key", "testText": "text"}
Cloud Flare Workers Code:
addEventListener('fetch', function (event) {
const { request } = event;
const response = handleRequest(request).catch(handleError)
event.respondWith(response)
})
async function handleRequest(request) {
const realBody = JSON.parse(`${await request.json()}`
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\f/g, "\\f"));
const stringifiedJSON = JSON.stringify(realBody);
const init = {
body: stringifiedJSON,
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
};
const initLog = {
body: JSON.stringify({ msg: { discountBodyStringified: realBody }}),
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
}
const responseLogger = await fetch("https://example.com/log", initLog)
console.log(responseLogger)
console.log(init)
const response = await fetch("https://example.com", init)
return new Response("tweet sent!")
}
function handleError(error) {
console.error('Uncaught error:', error)
const { stack } = error
const initLog = {
body: JSON.stringify({ msg: { error: stack || error }}),
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
},
}
const responseLogger = fetch("https://example.com/log", initLog)
return new Response(stack || error, {
status: 500,
headers: {
'Content-Type': 'text/plain;charset=UTF-8'
}
})
}
problem is not in the code, the problem in request which you are or front app is sending somewhere you lived extra comma or didnt close field.
For example:
{
"name": "Alice",
}
this will give same error as SyntaxError: Unexpected token \n in JSON at position because extra comma is there or
{
"name": "Alice
}
this also will throw error because I didnt close quotes

Update item in another site collection in sharepoint 2013

I need to update item in another site collection according to this article I make my code like this
<script type="text/javascript">
$(document).ready(function () {
var otherSiteUrl = "<sitecollectionurl>";
var listName = "TestList";
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": {
"type": itemType
},
"Title": "updated title"
};
$.ajax({
url: otherSiteUrl + "/_api/contextinfo",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (contextData) {
alert(contextData.d.GetContextWebInformation.FormDigestValue);
$.ajax({
url: otherSiteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?#target='" + otherSiteUrl + "'",
method: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue
},
success: function (data) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
});
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
I used
"X-RequestDigest":
contextData.d.GetContextWebInformation.FormDigestValue
after that I chenge ajax header like
"X-RequestDigest":
$("#__REQUESTDIGEST").val(contextData.d.GetContextWebInformation.FormDigestValue)
for both RequestDigest I got this error:
Invalid JSON. A token was not recognized in the JSON content
after that I chenge ajax header as
How can I update item successfully in another site collection with api?
eventually, I can edit item in another site collection.I just little change in my code.
first, most important part is library full name dose not contain List I use this url to find out library full name .
[Site url]/_api/web/lists/GetByTitle('List Name')/ListItemEntityTypeFullName
then I change metadate as
"__metadata": { "type": 'SP.Data.DocumentsItem' },
second I added
"X-HTTP-Method": "MERGE" , "If-Match": "*"
to header like:
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},

ReactJS - How to deserialize and show a serialized JSON response?

I'm getting a serialized JSON body from our API like the below example: '
{
"_embedded": [
{
"id": 1,
"vulnerable": false,
"systemId": "something",
"friendlyName": "a friendly name"
},
]
}
How to show just the key/value friendlyName? I'm using axios to get the response. This is my code:
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
transformResponse: axios.defaults.transformResponse.concat((data) => {
console.log(data) // this should now be JSON
})
}).then(({ data })=> {
this.setState({
data: houses.friendlyName
});
})
.catch((err)=> {
console.log(err);
});
I think I'm supposed to transform the data, but I don't know how. Thanks for any help.
Edit: This is how the response is shown in console:
_embedded:
0:
friendlyName: "a friendly name"
id: 1
systemId: "GE8BP2IACH7"
vulnerable: false
So, how do I deserialize it?
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
}).then(function (response) {
this.setState({data:response._embedded.friendlyName})
})
.catch(function (error) {
console.log(error);
});

Node Getting JSON_PARSING_ERROR

I am trying to call GCM notification by using POST.
The code I am using is :
var jsonbody={"to": "/topics/global",
"data": {
"title": "TestTitle",
"is_background": false,
"message": "Testmessage",
"image": "",
"payload": {
"team": "India",
"score": "5.6" },
"timestamp": "2016-12-13 16:32:05"
}
};
var request = require('request');
request.post({
headers: {'content-type': 'application/json',
Authorization:'key=(my key)'},
url: 'https://fcm.googleapis.com/fcm/send',
BODY: jsonbody
}, function (error, response, body) {
if (error) {
console.log('failure ' + error);
} else {
console.log('success '+response + 'and ' +body);
}
});
I am getting error as :
success [object Object]and JSON_PARSING_ERROR: Unexpected token END
OF FILE at position 0.
I was actually missing something :
body: JSON.stringify(jsonbody)
Rest all was correct.

Error processing request stream. JSON text specified is not valid

I used this code
function updateListItem(itemId, listName, siteUrl, title, success, failure) {
var metatdata = "{ '__metadata': { 'type': 'SP.Data.TestListListItem' }, 'Title': "+title+"}"
getListItemWithId(itemId, listName, siteUrl, function (data) {
$.ajax({
url: data.__metadata.uri,
dataType: "json",
contentType: "application/json;odata=verbose",
method: "POST",
body: metatdata,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Content-Length":metatdata.length,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function (data) {
alert("success in ajax");
console.log("Item in success ajax");
console.log(data);
success(data);
},
error: function (data) {
alert("waiting for success in ajax");
console.log("Item in error ajax");
console.log(data);
failure(data);
}
});
}, function (data) {
failure(data);
});
when i checked it using console,it shows "Error processing request stream. JSON text specified is not valid",I think i can't able to read text value from JSON Response and I tried lot.Please help me guys..Thanks in Advance
function updateListItem(itemId, listName, siteUrl, title, success, failure) {
getListItemWithId(itemId, listName, siteUrl, function (data) {
var item = { '__metadata': { 'type': 'Microsoft.SharePoint.DataService.TestListItem' }, 'Title': title };
$.ajax({
url: data.__metadata.uri,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": data.__metadata.etag
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}, function(data){
failure(data);
});
}
function getListItemWithId(itemId, listName, webUrl, success, failure) {
$.ajax({
url: webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d);
},
error: function (data) {
failure(data.responseJSON.error);
}
});
}