Folks,
Trying to understand returning and forming JSON responses.
The following code returns the object as a single string:
res.send(JSON.stringify(data));
Output to the browser:
{"Count":1,"Items":[{"dbsource":{"S":"x"},"number":{"S":"5002820"},"name":{"S":"blah,foo"},"expiration":{"S":"06/13/2015"},"type":{"S":"bar"}}]}
Dont I want the JSON output to be more readable, ie :
{
"one": "two",
"key": "value"
}
What should i change JSON.stringify(data) to? Ideally I want the response to be used as an API endpoint.
Thanks!
You are almost there. Use stringify with spaces
var str = JSON.stringify(data, undefined, 2);
The above string will have indentation with 2 spaces.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Related
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)
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.
I am running a Javascript function on the latest version of Mozilla which receives a string which I want to convert to a JSON object. The conversion seems to be failing.
The string is being generated on the server side in a Java function:
result = "[{ \"userID\": 1 \"firstName\":\"John\" \"lastName\":\"Sheridan\" }{ \"userID\": 2 \"firstName\":\"Michael\" \"lastName\":\"Geribaldi\" }]";
(note that I am attempting to return an array of values for a list).
The code on the client side is the ajax callback shown below:
var successFunc = function(data, textStatus, jqXHR)
{
alert("Data: "+data);
var obj = $.parseJSON(data);
alert("Object: "+obj);
}
Apparently, the data is coming back to the callback and is being displayed in its string form, but the JSON parser is failing because the second alert is failing to appear. I am sure something is wrong with my string but am having trouble figuring out what. The debugger is not telling me anything, I am just seeing a silent failure.
I have also attempted this using the JSON.parser() function. I am seeing the same thing. I am making a mistake somewhere. Can someone tell me where?
Your json is not valid, you are missing comma
In order to parse your json should be like this
[
{ "userID": 1, "firstName":"John", "lastName":"Sheridan" },
{ "userID": 2, "firstName":"Michael", "lastName":"Geribaldi" }
]
JSON is a format where data is in key:value pairs separeted by , and key and value are enclosed in double quotes, where objects are enclosed in {} braces and array is enclosed in [] hope you have got the your mistake that where your json is lacking.
"[{
\"userID\": 1 ,
\"firstName\":\"John\",
\"lastName\":\"Sheridan\",
},
{
\"userID\": 2 ,
\"firstName\":\"Michael\",
\"lastName\":\"Geribaldi\" }]"
I am trying to parse in this result of data which i obtained from xml conversion to json parsing :
var output = [{"SearchResults:searchresults":{"$":{"xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation":"someurl","xmlns:SearchResults":"someurl"},"request":[{"keyval":["keydata"]",...}]}]}]}]}]}]}}]
How to get keydata of keyval. I tried parsing and stringify also but no results.
Thanks in Advance
Your unreadable comment does not really shed much light on the issue. My guess is that you retrieve JSON though AJAX with jQuery, thus your JSON is already decoded when you display it in the console (that's what jQuery is good at) and you no longer have a JSON string but good old JavaScript array. Your question is probably the classical "how do I read a deeply nested piece of data" we see a lot here.
Using proper indentation everything's cleaner:
var output = [
{
"SearchResults:searchresults": {
"$": {
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "someurl",
"xmlns:SearchResults": "someurl"
},
"request": [
{
"keyval": [
"keydata"
]",
...
First item of array:
output[0]
First key:
output[0]["SearchResults:searchresults"]
Next level:
output[0]["SearchResults:searchresults"]["$"]
... etc.
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.