NODEJS unable to send json formatted response? - javascript

I am trying to send json response from my nodejs application to the client. However, the response does not seem to be in the right format can someone point me what is it that i am doing wrong ?
Below is subset of my code
var insertdata = "create-fail";
var updatedata = "update-fail";
var deletedata = "delete-fail";
insertdata = "{ create:pass ,";
updatedata = "update:pass ,";
deletedata = "delete:pass }";
var jsondata = insertdata+updatedata+deletedata;
res.send(JSON.stringify(jsondata));
Output browser:
"{ create:pass ,update:pass ,delete:pass }"

JSON.stringify should receive an object, not a string.
var jsondata = {'create':'pass', 'update':'pass', 'delete':'pass'};
res.send(JSON.stringify(jsondata));

This is an object:
object = { hello: 1 }
This is a string:
string = "{ 'hello': 1 }"
The string looks similar to the object, because its format is JSON (Javascript Object Notation), which is inspired in the way object is declared above.
Objects can't travel across the internet, but strings can. You can go from object to string using JSON.stringify():
string = JSON.stringify(object)
When you receive it on the other side, go back using JSON.parse():
object = JSON.parse(string)

jsondata is a string - and then you're stingifying it. If you're using jQuery, use $.parseJSON or use the json2 library.

Related

Get JavaScript object from database

I've a table in a SQL DB in which I store a JavaScript object like this:
{content: ['First paragraph','second paragraph']}
I get it from DB and try to pass to a function which needs an object formatted like it:
this._schedaService.getObjectFromDBToPrintPdf().subscribe(data => {
pdfMake.createPdf(data).download('tempPdf.pdf');
});
The problem is that data is always a string.
I've tried JSON.parse(data) but (obviously) doesn't work.
If I write
cont temp = {content: ['First paragraph','second paragraph']};
it works.
Does anyone have a good idea?
If you use the JSON.parse JavaScript function, e.g.
var data = JSON.parse("{content: ['First paragraph','second paragraph']}");
you will receive the following error:
Uncaught SyntaxError: Unexpected token c in JSON at position 1
because your input string does not have a valid JSON object syntax.
Your input string should have this format:
'{"content": ["First paragraph","second paragraph"]}'
I solved it in a tricky way: since JSON.parse is a specific type of the eval function, I just focused on JSON. The only solution (that I've found 'till now) is:
var str = "{content: ['First paragraph','second paragraph']}";
var obj = eval("(" + str + ")");
N.B. typeof(obj) returns
object
Here is an useful link.

Parse JSON Data from a String variable and convert it to objects in a $scope.variable

I have a string variable containg JSON data as below.
var jsonstring = [{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"},
{"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"},
{"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]
I want to get this string and convert it to an array of objects (which would be a $scope.variable) so that i can be able to access each object individually.
I tried to use the JSON.parse() but it gets the entire string into one object instead of multiple objects.
Kindly help me with this.
You've to parse the entire string with JSON.parse.
Each object in the array can then be reached like any other array, e.g. myArray[index], myArray.map() / myArray.forEach() etc
[{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"},
{"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"},
{"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]
This is an array object.It's not a string object.
You can try again like this:
var jsonString = "[]";
var json = JSON.parse(jsonString);
var jsonstring = '[{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"}, {"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"}, {"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]';
$scope.variable = JSON.parse(jsonstring);
The JSON.parse() method parses a string as JSON.
Code in your question, shows that you are trying to parse a JS object and not a string.
In the following example, you get an error if you try to parse a JS object.
var jsonstring = [{},{}];
JSON.parse(jsonstring); // ERROR Uncaught SyntaxError: Unexpected token o
The following works instead (please note jsonstring is a string and not an object here):
var jsonstring = '[{},{}]';
JSON.parse(jsonstring); // OK

How To Parse A String Of Concatenated JSON In Browser?

I'm using Socket.IO to move data to the browser. The data sent is a stream of JSON objects, and when it arrives at the browser, it becomes one large string of JSON. The problem is, this JSON can't be parsed by JSON.parse() because it's not "real" JSON.
The data structure can be arbitrary so a RegEx might not do the trick. And this current setup is only temporary. Eventually this stream of JSON will be pre-processed server-side so a stream will not need to be sent to the browser, so I'd like to keep the AJAX/Socket.IO setup I have right now instead of switching over to a JSON stream parser like OboeJS.
What can I do to parse this string of concatenated JSON?
For clarity, the JSON will look like this:
{"a":"A"}{"b":"B"}{"c":"C"}
And I'm trying to parse it in such a way that I can access them like:
console.log(Object.a) //A
console.log(Object.b) //B
console.log(Object.c) //C
In your particular case, you could use Array.prototype.reduce to merge all JSON objects into one:
var unstructuredJson = '{"a":"A"}{"b":"B"}{"c":"C"}';
var jsonArray = "[" + unstructuredJson.split("}{").join("},{") + "]";
var objectArray = JSON.parse(jsonArray);
var result = objectArray.reduce(function(result, item) {
Object.keys(item).forEach(function(propertyName) {
result[propertyName] = item[propertyName];
});
return result;
}, {});
document.body.textContent = JSON.stringify(result);
OP said in some comment:
[...] Each JSON might have nested data like {{}{}}{}{}{}
Then, above approach is broken on this case.
My two cents is that you should put some separator character when you stream these JSON objects and life will be easier: you'll be able to split parent objects easily and you'll just need to change split("}{") with the whole separator.
I suggest you that you use some character that will never happen as part of any property value. You can find a control character on this Wikipedia article: Control character
If each substring is valid JSON but the concatenated part isn't, you can turn the string into a valid array literal and use JSON.parse, then you can process each object using Array methods, e.g. forEach:
var s = '{"a":"A"}{"b":"B"}{"c":"C"}';
var obj = JSON.parse('[' + s.replace(/}{/g,'},{') + ']').forEach(function (obj) {
document.write(JSON.stringify(obj) + '<br>');
});
Or if you want it as a single object:
var s = '{"a":"A"}{"b":"B"}{"c":"C"}';
var obj = JSON.parse(s.replace(/}{/g,','));
document.write(JSON.stringify(obj));
You can use JsonParser to parse concatenated json objects:
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = new JsonFactory(mapper);
JsonParser parser = factory.createParser(YourJsonString);
List<YourObject> YourObjectList = new ArrayList<>();
Iterator<YourObject> iterator = parser.readValuesAs(YourObject.class);
while(iterator.hasNext()) {
YourObject yourObject = iterator.next();
loginSignalsList.add(yourObject);
}
Split the large string {a:'A'}{b:'B'}{c:'C'} and parse them individually

Javascript JSON.parse or directly access

When we can read a property directly from string:
var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde
Why do people use JSON.parse:
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
It is not a string, but Javascript object. String is given below
var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';
to make it object we use JSON.parse
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
In your first example, data is an object, but in your second example, data is a JSON string.
That's a major difference. You could call eval(data) to parse a JSON string, but that's very unsafe.
JSON.parse() expects a string. More specifically, a string with a JSON-encoded piece of data.
If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format.

Parse object to JSON

I have some web services that receive JSON data send by jquery method.
But I need to edit the object before send this data. Is there any way to parse a JSON object to a simple object in javascript, modify it and then parse it again to JSON. or maybe update this JSON object without parse it?
To go from a JSON string to a JavaScript object: JSON.parse, or $.parseJSON if you're using jQuery and concerned about compatibility with older browsers.
To go from a JavaScript object to a JSON string: JSON.stringify.
If I've already do this var myData = JSON.stringify({ oJson:{data1 :1}}); and then I want to update that information setting data1 = 2, what is the best way to do this?
var myData = JSON.stringify({ oJson:{data1 :1}});
// later...
parsedData = JSON.parse(myData);
parsedData.oJson.data1 = 2;
myData = JSON.stringify(parsedData);
Even better though, if you save a reference to the object before stringifying it, you don't have to parse the JSON at all:
var obj = { oJson:{data1 :1}};
var myData = JSON.stringify(obj);
// later...
obj.oJson.data1 = 2;
myData = JSON.stringify(obj);
var parsed = JSON.parse('{"a": 1}');
parsed.b = 2;
var string = JSON.stringify(parsed);
//string is: '{"a":1,"b":2}'
I think something like the following should work...
//Convert your JSON object into a JavaScript object
var myObject = JSON.parse(json);
//You can then manipulate the JavaScript object like any other
myObject.SomeValue = "new";
//Then you can convert back to a JSON formatted string
json = JSON.stringify(myObject);
As JSON is an JavaScript object you can simply manipulate it with JavaScript.
You could do something like this to get a javascript object:
var jsObject = JSON.parse(jsonString);
Then you could modify jsObject and turn it back into a JSON string with JSON.stringify.
This page has more information on it.

Categories

Resources