How to handle escaped sequences in JSON array with express - javascript

I am using node.js with express and I'm building an API that exposes an endpoint that must accept POST requests with a a JSON array of strings.
I'm having problems when I receive JSON arrays with special escaped characters like this one:
[\t"hello"\n, "world"\n\n]
Is there any way to ignore or parse this with express? I thought that app.use(express.json()); could handle this.
Everytime I receive one JSON array with escape characters it gives me this error:
SyntaxError: Unexpected token \ in JSON at position 1
at JSON.parse (<anonymous>)
at parse (...\node_modules\body-parser\lib\types\json.js:89:19)

Show me the code creating the JSON. Then I'll help you solve the problem, because working with existing JSON like that isn't right. JSON only should have something like:
{
"name1": "value1",
"name2": "value2",
"name3": "value3",
...,
"namex": "valuex"
}
Never let values go outside the quotemarks if they're a string.

Maybe the json returned in response api is string so looks like that => [\t"hello"\n, "world"\n\n].
Do you parse it already?
const array = `[\t"hello"\n, "world"\n\n]`
const parseArray = JSON.parse(array)
console.log(parseArray)

Related

How can I convert a javascript array to json format to serve as the response from a REST api

I am trying to figure out how to take an array of arrays and convert it to a json string to return via a REST api.
My server gets records from a database. Each record is in the form:
{"user":"some name","age":number}
I need to return the data in json format so that the REST specification is valid.
Sometimes I get a single record to return other times I get multiple records.
Below is a sample script I am using to test the syntax for converting into json format.
var resultSet = [];
resultSet.push({"user":"John Doe","age":43});
resultSet.push({"user":"Jane doe","age":29});
var myJson = JSON.parse(resultSet);
When I run this code using nodejs I get the following error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
Any suggestions would be very appreciated.
JSON.parse expects a string. You are passing an Array.
This works because the input is a string:
JSON.parse('[{"foo": "bar"}]')
This doesn't work because the input is an Array:
JSON.parse([{"foo": "bar"}])
Are you trying to return an Array or a string? If you are trying to return a string, then you should use JSON.stringify like this:
JSON.stringify([{"foo": "bar"}])

Why this JSON object cannot be parsed?

In my JavaScript file,
The declaring and json parse for the ajax response text is like this:
var subcats = JSON.parse(this.responseText);
The supposed responseText for the parsing is like this:
{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"}{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}
and it gives me this error:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 64 of the JSON data
what's the syntax error? help
Your JSON have multiple elements and therefore should be wrap in an Array/List like this
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"}{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
Hope it helps
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. So you can use it like this if you have a single item:
JSON.parse('{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager"}');
but in your case you have multiple items that should be wrapped inside brackets [] and separated by commas or there is SyntaxError:
JSON.parse('[{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager" }, { "presubcatId": "2", "precatId": "1", "presubcatName": "Marketing Manager"}]');
var string = '[{"presubcatId":"1", "precatId":"1", "presubcatName":"HR Manager" }, { "presubcatId": "2", "precatId": "1", "presubcatName": "Marketing Manager"}]';
var json = JSON.parse(string);
console.log(json);
Your JSON is invalid. You need change it like this:
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
your JSON data is invalid so that you are having problem,
var temp=[];
temp=[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
console.log(JSON.stringify(temp))
Your JSON have multiple elements. So it must be treated like Array. See below image.
Below is valid JSON structure.
[{"presubcatId":"1","precatId":"1","presubcatName":"HR Manager"},{"presubcatId":"2","precatId":"1","presubcatName":"Marketing Manager"}]
Your json object is not a valid json. You can check it on this site. It helps me a lot when I need to format or validate a Json object.
https://jsonlint.com/
Here is your json object formatted and it says what you are missing.

ionic 2 get data from malformed json

is there anyway i can get this malformed json format which is odd i have no control over this json manually so i need to get this data and manipulate it with rxjs observable from http get
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
I tried with your JSON in the console and this seems to work. In the map function I've used you can probably implement more generic replacement methods to alter the strings, but it works for this example.
function fixBadJSON(response){
let badJSON = JSON.stringify(response); // added this edit in case you don't know how to get the response to a string
let arr = badJSON.split('}\n'); // Looks like the JSON elements are split by linefeeds preceded by closing bracket, make into arr length of 3
let fixedArr = arr.map((item)=>{ // map the array to another, replace the comma at the end of the avatarImage key. elements in array should be proper JSON
if(item[item.length] != '}') item += '}'; //put the brackets back at thend of the string if they got taken out in the split, probably a better way to handle this logic with regex etc
return item.replace('jpg",','jpg"')
});
let parsedJSON = JSON.parse(JSON.stringify(fixedArr));
return parsedJSON
}
Take the JSON data you've posted up there and copy it to a variable as a string and test the function, it will return a properly formatted array of JSON data.
Call that when you get a response from your service to transform the data. As far as the observable chains and any async issues you might be seeing those are separate things. This function is just designed to convert your malformed JSON.

Javascript / Node - Convert json stored as text in DB to JSON object

I've been banging my head against a wall with this all day, I've looked at other questions and they all say use JSON.parse or something similar, but I can't get anything to work for the life of me.
I have an object stored as text in a PostGres DB:
{149804: [75319, 2887526, 2938701],3136977: [3482061,3482062]}
I have to read it into a variable and go through it's properties but i can't get it to work, if I do a JSON.parse I get a "SyntaxError: Unexpected number" on the first number {1...}.
I tried looking at the object properties without doing a parse to test it, but it keeps saying it doesn't have that property (with and without ' around the number in case):
if(selectedItems.hasOwnProperty(149804)){
console.log("HAS 149804");
}else{
console.log("DOESN'T HAVE 149804");
};
What am I doing wrong here?
That's because your JSON is invalid.
{149804: [75319, 2887526, 2938701],3136977: [3482061,3482062]}
should instead be
{"149804": [75319, 2887526, 2938701],"3136977": [3482061,3482062]}
Then JSON.parse will work. Object properties should be strings, not numbers.
A key name/index in JSON must be a string. Proper JSON would be:
{
"149804": [
75319,
2887526,
2938701
],
"3136977": [
3482061,
3482062
]
}

JSON.parse parsing JSON with nested objects

I'm attempting to parse a JSON string with nested objects received in the response of a post request. After running JSON.parse(responseText), the result is in the following format:
[{
"atco":"43000156407",
"location":{
"longitude":"-1.7876500000000000",
"latitude":"52.4147200000000000","
timestamp":"2013-03-19 11:30:00"
},
"name":"Solihull Station Interchange",
"road":"STATION APPROACH",
"direction":"NA",
"locality":"Solihull",
"town":"Solihull"}, ...
I thought I would then be able pull values out using the following as an example, but all I get is undefined.
var atco = json[0].atco;
I've also tried json[0][0] but that returns an individual character from the JSON ([) . Does this indicate the JSON hasn't parsed correctly, or is this expected behaviour and I'm just referencing incorrectly?
This means that your JSON is being double encoded. Make sure you only encode it once on the server.
As proof, after you've parsed it, parse it again.
var parsed = JSON.parse(resposneText);
var parsed2 = JSON.parse(parsed);
alert(parsed2.atco);
Either that, or you're parsing it but then trying to select the data from the original string. This would obviously not work.

Categories