Get JavaScript object from database - javascript

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.

Related

Can't parse my JSON into an object in javascript

I am working on a parser for a text file. I am trying to parse some JSON strings into objects so I can easily display some different values on a webapp page (using flask). I am passing the strings into my html page using jinja2, and trying to parse them objects in javascript.
function parseLine(x) {
var obj = JSON.parse(x);
document.write(obj.timestamp1);
}
I am getting this error:
SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
in the console browser. I have found many stackoverflow questions with that error, but the suggestions do not fix my problem.
If I use a dummy string, surrounded by single quotes: '{"test": "1234"}' it works fine.
If I need to include anymore information I can.
Had similar issues but was able to solve it using this way using the
reviver parameter on JSON.parse()
var Person = {}
// an empty person object
//sample json object, can also be from a server
var sampleJson = {'name': 'Peter', 'age': "20"};
//use the javascript Object.assign method to transfer the json from the source[JSON.parse]to the target[Person]
// the source is JSON.parse which take a string argument and a function reviver for the key value pair
Object.assign(Person, JSON.parse(JSON.stringify(sampleJson),
function (k, v) {
//we return the key value pair for the json
return k, v
}
)
)
console.log(Person.name) //Peter
console.log(Person.age) // age

NODEJS unable to send json formatted response?

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.

Reading Values of JSON Message

I have been struggling with a few lines of Javascript code which should be straightforward. I have reduced my JSON String to the one found hereafter. The first alert in the code hereafter generates the following message:
{"list":[{"text":"Text1", "created_at":"Date1"},{"text":"Text2", "created_at":"Date2"}]}
However, the second alert generates the following error in IE:
Error: Unable to get value of the property '0': object is null or undefined
var data = "{\"list\":[{\"text\":\"Text1\", \"created_at\":\"Date1\"},{\"text\":\"Text2\", \"created_at\":\"Date2\"}]}";
alert(data);
alert(data.list[0].created_at);
Would anyone understand why I am receiving this error?
data is an ordinary string; it doesn't have any properties.
You want to parse the JSON in the string into a Javascript object:
var obj = JSON.parse(data);
You are using a string with Json formatting, but is not JSON itself.
You should use this:
var data = {"list":[{"text":"Text1", "created_at":"Date1"},{"text":"Text2", "created_at":"Date2"}]};
alert(data.list[0].created_at);
Or use:
var jsonData = JSON.parse(data);
alert(jsonData.list[0].created_at);

Javascript: Parse JSON output result

How can i retrieve the values from such JSON response with javascript, I tried normal JSON parsing seem doesn't work
[["102",true,{"username":"someone"}]]
Tried such codes below:
url: "http://somewebsite.com/api.php?v=json&i=[[102]]",
onComplete: function (response) {
var data = response.json[0];
console.log("User: " + data.username); // doesnt work
var str = '[["102",true,{"username":"someone"}]]';
var data = JSON.parse(str);
console.log("User: " + data[0][2].username);
Surround someone with double quotes
Traverse the array-of-array before attempting to acces the username property
If you are using AJAX to obtain the data, #Alex Puchkov's answer says it best.
So the problem with this is that it looks like an array in an array. So to access an element you would do something like this.
console.log(obj[0][0]);
should print 102
Lets say you created the object like so:
var obj = [["102",true,{"username":someone}]];
this is how you would access each element:
obj[0][0] is 102
obj[0][1] is true
and obj[0][2]["username"] is whatever someone is defined as
From other peoples answers it seems like some of the problem you may be having is parsing a JSON string. The standard way to do that is use JSON.parse, keep in mind this is only needed if the data is a string. This is how it should be done.
var obj = JSON.parse(" [ [ "102", true, { "username" : someone } ] ] ")
It depends on where you are getting JSON from:
If you use jQuery
then jQuery will parse JSON itself and send you a JavaScript variable to callback function. Make sure you provide correct dataType in $.ajax call or use helper method like $.getJSON()
If you getting JSON data via plain AJAX
then you can do:
var jsonVar = JSON.parse(xhReq.responseText);

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.

Categories

Resources