Parsing JSON with endline characters when receiving it from the server - javascript

I have a JSON that looks like so:
{
"response": {
"event": "Other",
"time_opened": "2014-09-09 10:09:07",
"time_updated": "2014-09-10 09:34:55",
"name": "blablablablablabla",
"current_status": "blablabla
blablablablablablablablablablablabla
blablablablablablablablabla
blablablablablablablablabla
"
}
}
I get "Uncaught SyntaxError: Unexpected token" on JSON.parse. After research I couldn't figure out how to wrangle it. Sorry if duplicate, but I'm a little lost here.

The problem was resolved with appropriate encoding server side.

Related

What is Unexpected token a in JSON at position 0?

I am getting an error that says SyntaxError: Unexpected token a in JSON at position 0
and I cannot find any information on what "a" means. I know that the JSON is not undefined.
Can anyone help me understand what is causing this error?
Here is the code block that is causing the error:
let db_creds = await getDBCredentials();
console.log(db_creds)
const pool = new Pool(JSON.parse(db_creds['SecretString']));
console.log(pool)
Unexpected Token < in JSON at Position 0. From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON. ... json() method on the fetch object, it can result in a JavaScript exception being thrown.
What Is JSON and How to Handle an “Unexpected Token” Error
Well for me it was because the port was already in use and it must be sending HTML, you can try killing the port by running the below command in cmd(admin mode)
taskkill /F /IM node.exe

Reference POST body in the Tests

I want to reference the POST body in my tests.
Raw post body
{
"AppName": "application1",
"AppVersion": 1,
"DeviceId": "UnitTestDevice",
"UserName": "test1"
}
Tests
console.log(body.UserName);
This returns an error saying: "ReferenceError: body is not defined"
How do I go about referencing UserName in my tests?
You can log it by using:
console.log(pm.request.body);
(for the request)
or
console.log(responseBody);
(for the response)
In your specific case, let's assume that you want the request. Then:
console.log(JSON.parse(pm.request.body).UserName);

Azure Function with Node.js can't access SQL database: Entry point problem?

I am trying to connect an Azure Function to a SQL-Database that I also created in Azure. Sounds pretty simple and Microsoft even has a pretty good POC tutorial for it. However, in my case the Azure Function is dropping "entryPoint" errors that I am not able to resolve.
I checked some other stackoverflow discussions (Can't connect Node.js server to Azure SQL Database) and googled the hell out of it. Unfortunately it seems like none of this is helping. I updated the "function.json" to set my entryPoint as shown below.
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"access": "listen",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"entryPoint": "index",
"direction": "out",
"name": "res"
}
]
}
My index.js code is a very trivial try to connect to the database and tell me about the success.
var Connection = require('tedious').Connection;
var config = {
userName: 'XXXX',
password: 'XXXX!',
server: 'XXXX.database.windows.net',
// If you are on Microsoft Azure, you need this:
options: {encrypt: true, database: 'XXXXX'}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
console.log("Connected");
});
Normally this should connect to the database and print a "Connected" to the console but somehow it shows this error:
[Error] Executed 'Functions.TediousTest' (Failed, Id=XXXXXXX)
node exited with code 1
[error] Worker was unable to load function TediousTest: 'Unable to determine function entry point. If multiple functions are exported, you must indicate the entry point, either by naming it 'run' or 'index', or by naming it explicitly via the 'entryPoint' metadata property.',[error] Worker XXXXXX uncaught exception: ReferenceError: executeStatement is not defined
Hopefully this is enough information to understand my problem. The database has no special firewall etc. at the moment. Besides it seems like the code snippet isn't even able to get in touch with the firewall. Thanks in advance.
I believe you haven't exported your function properly based on the error message - basically missed the module.exports line.
I guess your code looks something like this
...
async function TediousTest() {
...
}
If so, just add this line to the end
module.exports = TediousTest;

Live streaming JSON data with javascript

I want to livestream telemetry data formatted in JSON from a websocket to a browser using javascript.
A websocket is created on a server X.X.X.X using native c and the websocketd wrapper on port 8080. A client (IP: Y.Y.Y.Y) shall connect to the very same server via https on port 80 (https://X.X.X.X:80) and shall receive javascript code which tells it to grab livestream data from the websocket (ws://X.X.X.X:8080) and refresh some values on the website with the values from this stream.
The data can exemplarily look like this:
{
"name of system": {
"RSSI": {
"rssi": "0",
"adc1": "0.00",
"adc2": "0.00",
"rxBatt": "0.00",
"swr": "0"
},
"ASS": {
"airspeed": "0.00"
}
}
}
{...}
and so on...
This frame shall be repeated e.g. in a 500ms interval and is sent with no whitespaces nor newline characters.
I tried parsing this already with JSON.parse() but my browser console returns following error: "Uncaught SyntaxError: Unexpected token *" or "Unexpected token {". Is this because of wrongly implemented JSON code, although I checked it several times?
My question is now: Is JSON.parse really capable of livestreaming? If not, are there libraries which are, or am I better off with a completely new solution?
Best regards
If the JSON parser is encountering an asterisk, as suggested by Unexpected token *, then your JSON is malformed, as that's not a valid character in JSON (outside of a string).
I'd recommend examining the message being received and visually check that it's valid JSON. Something like:
webSocket.onmessage = function(event) {
console.log(event.data);
}
Then, you can check your browser's developer console (usually Cmd-Shift-I on a Mac or F12 elsewhere) to see what you're actually receiving.

Output bindings not picked up or present in Javascript Azure Functions

I'm having a bit of difficulty getting my simple Azure Function to dump a JSON payload into a CosmosDB. Here is the desired setup:
[HTTP TRIGGER] -> [JS FUNCTION] -> [INSERT JSON TO COSMOS DB]
I've added a cosmosDB output binding via Integrate in the web console
I know this part works because it will auto-create the collection upon running.
However, this is where my success ends.
I've included my code here. Maybe there is something obvious that I have missed:
function.json
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req"
},
{
"type": "http",
"direction": "out",
"name": "res"
},
{
"type": "documentDB",
"name": "outputDocument",
"databaseName": "outDatabase",
"collectionName": "MyCollection",
"createIfNotExists": true,
"connection": "mydocdb_DOCUMENTDB",
"direction": "out"
}
],
"disabled": false
}
index.js
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
context.bindings.outputDocument = {test: "hello world"}
context.done();
};
snippet output of context.log(context)
I've also peeked into the context variables, and it seems that the outbund bindings not there. I would have expected to see outputDocument here:
bindings:
{ req:
{ originalUrl: 'https://log-ugly-url-here',
method: 'POST',
query: [Object],
headers: [Object],
body: [Object],
params: {},
rawBody: '{\n "name": "Azure"\n}' } },
bind: [Function],
Executing this function in the portal gets a 200 OK, but no values show up in my cosmosdb collections.
No errors are shown anywhere.
Can anyone see what I might have missed?
Updates
It was recommended that I try to use JSON.stringify() around the payload, per this document:
context.bindings.outputDocument = JSON.stringify({test: "hello world"});
However, this has not resolved the issue. I've noticed that the documentation under the binding config sections does not recommend this strategy.
Update - Nov. 8, 2017 (10:12 AM)
I was using the Data Explorer blade in azure to see if there were results in my collections. I decided to use Robo 3T Mongo client. Now, when I query the collection I get the following error:
Error: error: {
"_t" : "OKMongoResponse",
"ok" : 0,
"code" : 1,
"errmsg" : "Unknown server error occurred when processing this request.",
"$err" : "Unknown server error occurred when processing this request."
}
I tried to look at the logs for this cosmosdb, but no errors show up.
I ran into this as well. Kept banging my head until I saw this:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-integrate-store-unstructured-data-cosmosdb
“At this time, the Azure Cosmos DB trigger, input bindings, and output bindings work with SQL API and Graph API accounts only“
Looks like there is a bug in Azure that accidentally corrupts the database.

Categories

Resources