Convert Javascript object to a JSON string - javascript

I want to directly convert a javascript object to string. I used following code.
var foo = {};
foo.test1 = test1;
foo.test2 = test2;
foo.test3 = test3;
var jsonObj = JSON.stringify(foo);
It works fine but it uses the json2 javascript library. However I need to do this in plain javascript without using any libraries. I know creating the json feed using passed parameters will work like this.
var jsonObj = "{\"test1\":\"" + test1+ "\",\"test2\":\"" + test2+ "\",\"test3\":\"" + test3+ "\"}";
However if the passed parameters(test1, test2 and test3) contains double quotes it will have issues.
What is the best approach to achieve this?
Thank you

You should escape the double quotes by performing a String.replace(/"/g, "\\\"") on each key and member. For this to work however, you need to guarantee that you will only have simple strings/ numbers in your JS object.
FYI, it should be noted that the json2 library will only be used when a native implementation of JSON does not exist; all modern browsers have JSON support build in (IE < 8 is the noticable exception).

I think you've totally misunderstood what JSON is. JSON Stands for Javascript Object Notation.
What you haven't realised is that foo is already an object and further have you actually thought about what you'd be coding to access jsonObj ?
Here's a hint jsonObj.test1 : looks familiar doesn't it.
What you might be trying to do is to create a string that looks like JSON content but isn't in fact an object. That's a different question though.
Hope this helps.

Related

How do i work with JSON in javascript

Recently, i have been working with JSON from a url.
I was hoping to use only javascript to interact with the json file.
Hence, i found out about this:
How can I open a JSON file in JavaScript without jQuery?
I used the answer from Drew, but the question now is how do i work with the Object?
Object {success: true, rgInventory: Object, rgCurrency: Array[0], rgDescriptions: Object, more: falseā€¦}
This is the result from using Drew's answer.
I hope my question is understandable.
So, JSON stands for Javascript Object Notation.
Think that as a way to describe a object in Javascript in a human readable manner.
So if you downloaded a JSON file it is a json in text plain format, in order to work with this you first need to transform this text notation in a actual object by parsing it.
Ex:
var asText = '{"hello": "world"}';
var asObject = JSON.parse( asText );
console.log( asObject.hello );
To access into success value write var successValue = object.success.
that was your question?

How to parse variables to JSON Object (Javascript)

I want to be able to parse external variables into a JSON object.
Something like this would do:
var username = "zvincze";
And using that variable to parse a JSON object:
var json = '{"username":"VARIABLE_GOES_HERE"}'
var obj = JSON.parse(json);
This is a very simple question that I can't seem to figure out. In fact, I don't even know if there's a way to actually acheive something such as this.
You need to distinguish carefully between JSON and JavaScript objects. They are two entirely different things.
JSON is a language-independent character-based data representation that is used for data interchange. For instance, if you are sending data to a server, it needs to be in string form, so you would need to convert your data into JSON. If you are receiving data from a server, and it is JSON format, you need to convert it into a JavaScript object so you can use it in your JavaScript program.
JSON actually has nothing to do with JavaScript. For example, JSON could be used as a string-based data representation for Java programs exchanging data. Java and pretty much all other languages provide their own library routines for converting their native data into JSON and vice versa.
The only relationship between JSON and JavaScript objects used in JavaScript is that a JSON string looks much like a JavaScript object literal, with some additional restrictions, such as that keys must be quoted, that it cannot hold certain data types such as functions, and that it cannot hold circular references.
The "JS" part of "JSON" does not indicate that JSON is a basic JavaScript data structure, or that JSON is used in JavaScript for representing or manipulating data. It merely comes from the fact that, as mentioned above, the format of a JSON string is loosely modeled after that of a JavaScript object literal.
In normal day-to-day JavaScript programming, you will never use JSON, and don't need to worry about it. You will need to worry about JSON only when, as I said, you are sending data to somewhere, or receiving data from somewhere, that expects JSON as the data format. That is the case when making ajax calls, of course, but actually, even then, since jQuery's $.ajax will automatically convert data to and from JavaScript objects if you tell it the right types, even in that case you do not normally need to worry about JSON.
Note by the way that JSON can represent primitive values, not just JavaScript objects. For example, "1" is valid JSON which represents the number 1.
As I understand your question, you want to create a JavaScript object (not JSON) which contains as one of its values that of the variable username. You create a JavaScript object with regular old JavaScript object literal format, in this case
{username: username}
This means, create an object, with a single key named "username" (quote it if you please), whose value is that of the variable username. Again, unless you plan to send this object somewhere that expects a JSON string representation, there is no need to even think about JSON in this case.
In theory, yes, as one answer suggested, you could create a JSON string with the value of username "interpolated", using string arithmetic like '{"username":"' + VARIABLE_GOES_HERE + '"}', and then convert that JSON string into a JavaScript object using JSON.parse. However, there is absolutely no reason to jump through these hoops, when you can simply write the JavaScript object as a normal JavaScript object literal.
Another answer shows a way to define a regular JavaScript object, and then turn it into JSON using JSON.stringify. However, again, in your case, there is no need to do this unless you are planning to send the object somewhere.
Yet another answer shows a way to define a regular JavaScript object, then stringify it into a JSON string, then immediately parse it back into a JavaScript object, which will be exactly the same object you started with before stringifying and parsing. There's absolutely no need to do this.
One sees no small number of questions on SO trying to somehow manipulate or search or replace within JSON, using regexps for example. There are almost no cases where you need to even think of doing such a thing. JSON has two fundamental operations: converting values into JSON, and converting JSON into values. Both of those are built into the language in the form of JSON.stringify and JSON.parse, that do their jobs with absolute reliability and performance. If for some reason you need to modify data which is in JSON string format, don't manipulate the string; all you need to do is parse it into a JavaScript value, manipulate the value, and then convert it back into JSON.
Unfortunately, for unknown reasons, many JavaScript programmers who are learning the language, including many who have posted questions here on SO, have developed the misperception that JSON is a JavaScript object, or that they must think about JSON and stringifying and parsing in order to deal with plain old JavaScript objects, which is very much not the case.
Minor point, but you use the term "parse" in your question. I see more and more people using this word for some reason to mean "access" or "retrieve" or "extract". Actually, "parse" has a very specific meaning: to analyze a string-based representation of information (such as a program or data object), according to a particular grammar, into some suitable computer-friendly form for further processing. What JSON.parse does is parsing in this sense, because it is analyzing a string-based representation of information according to the JSON grammar into a JavaScript object for further processing.
You can simply concatenate strings like below...
var json = '{"username":"' + VARIABLE_GOES_HERE + '"}'
in your case:
var username = "zvincze";
var json = '{"username":"' + username + '"}';
Happy coding....
I think what you're doing is sort of odd. The object you create is json by definition (JavaScript Object Notation).
var obj = {};
obj.username = "zvincze";
//obj is now json
var str = JSON.stringify(obj);
//str == {'username':'zvincze'}
JSON.parse(obj) should fail since obj is already json.
Without messing with concatenation var json = '{"username":"'+ userName +'"}' you can:
var ob = {}; // or simply: var ob = {username:"zvincze"};
ob.surname = "Zvincze";
ob.name = "Zachary";
ob.id = "5182842";
var json = JSON.stringify(ob);
var obj = JSON.parse(json);
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
var json = JSON.stringify({username:"zvincze"})

Alternative to eval() javascript [duplicate]

This question already has answers here:
What are the Alternatives to eval in JavaScript?
(11 answers)
Closed 7 years ago.
I work mainly with javascript, Jquery, knockout, etc
The thing that attracted eval() to me is
var a = 5;
var b = 10;
eval("a+b");
//Gives me output 15
Note: I work in cases where the value of a and b changes dynamically
In my work I'm dealing with a lot of dynamic objects from json, knockout, etc. So eval solves most of my problems.
But as I read I found there are so many issues with eval() like slowing down etc.
I searched a lot and haven't found any substitute for eval() when i have to evaluate equation obtaining as string into equation as object.
Can anyone suggest a plugin or function alternative to eval() keeping in mind the example i have given above
Problem:
I'm creating a Table from Json data using knockout mapping. So that what ever the format of json is the table is generated. I also calculate some field using knockout computed.
Right now I use hard-coded
self.Salary = ko.computed(function(){ return self.salaryEqn() && eval(self.salaryEqn()).toFixed(2); })
self.salaryEqn(salEqnTxt);
I want to execute these equations dynamic. I can create it dynamicaly as string but to eval them is the issue I'm facing.
I want solution for
Is there a way to calculate a formula stored in a string in JavaScript without using eval?
Like a formula
"self.Salary = ko.computed(function(){ return self.salaryEqn() && eval(self.salaryEqn()).toFixed(2); })"
Javascript is a very flexible language in this regard. There are very very few cases where eval() is the right answer to any given question, and it certainly isn't necessary here.
If your a and b variables are part of an object, you can access them with string subscripts:
ie myobj.a could also be referenced as myobj['a'].
From that, you can use a variable for the subscript, and thus you can reference any element in myobj dynamically -- ie:
var myobj = {a : 5, b : 10};
var dynamicProperty1 = 'a';
var dynamicProperty2 = 'b';
//gives 15.
alert( myobj[dynamicProperty1] + myobj[dynamicProperty2] );
No eval() required. You can build the dynamicProperty strings however you wish, so there's virtually infinite flexibility.
If your a and b variables are globals, JS globals in the browser are actually children of the window object, so you can still use this technique even with globals.
ie your global variable a could also be accessed via window.a or window['a'], with the latter option allowing you to do the same dynamicProperty trick described above.
Hope that helps.
do you mean that you want to calculate an equation that you can't know until you've received it?
if so see Calculate string value in javascript, not using eval .
in short:
eval CAN be used sometimes, but only if the equation string comes from a trusted source, and there you need something like evaluating dynamic equations.
maybe using window['var' + num] might be more useful for you. i don't quite understand your question sorry.
If you can collect them under an object like root = {a: 1, b: 2}, then
Object.observe(root, function(newValues) {
res = newValues.object.a + newValues.object.b;
});
can keep your res variable up to date whenever the a or b changes
It looks like you are trying to do dynamic equations created by a user.
For example it could be 'a+b+c' or 'dog+cat', and you don't know.
The best way to handle user-input equations like that is to parse the text into tokens and then translate the tokens into values/operands.
That's a lot of work, but there are pre-rolled solutions. For example, math.js
Check more alternatives to eval in this question and another one here which both might be considered a duplicate...
I understand this is a link only answer, but it will for sure be helpful to others searching for alteratives to eval.

JSON that contains functions

I have a website that returns a JSON-like data structure like this:
{
"name":"tom jones",
"no": 123,
"storedproc": function(){
callbuyer(0123);
}
}
I'm getting this data using $.ajax() with dataType "JSON". Unfortunately, my $.ajax() calls the error callback because my data contains a function().
How can I parse this correctly? I really need to store the function in a variable and call it later.
That is simply not legal JSON (as you know given the title of the question) See the offical JSON syntax. The nice thing about real JSON is that one can use JSON.parse which safely wraps an eval call.
While eval could be used, I would suggest revisiting the architecture of your application and find some other way to do what you are trying to do.
In particular, I would have the server return the 0123 only, and let your client keep the logic that lets it know, in certain cases, which functions apply (in the scenario here, the function would be callbuyer).
This should work because you say you want to call the function which is the value of the storedproc later. Since the body of this function contains a call to callbuyer it follows that your client side script knows what callbuyer is. The trick is for your server not to send back arbitrary, unconstrained functions, but rather data that your client can exploit somehow using the knowledge it has about the overall application.
Could you arrange to have the server return JSON like this:
{"name":"tom jones",
"no": 123,
"storeprocFn": callbuyer,
"arg": "0123"};
Then your callback function can call the callbuyer function and pass arg
Use eval to interpret the string as a javascript object. You won't be able to use the JSON data type though. I believe what you need to do is use 'text' as the dataType for the $.ajax call. Then do something like:
var data = eval('(' + text + ')');
Should work. Of course, eval is evil. But it would solve your problem. As long as you can guarantee there isn't anything malicious in the text (no unsanitized, user entered data) then you should be ok.
AFAIK, functions are left out when using JSON.stringify, it's just not meant to be used to clone full objects (props and methods). However, you might be able to pass the function body as a string.Say you decide on a string format like func=>var foo = 'bar'; return foo;. This should be passed as a regular JSON string, after parsing the object you could then iterate all properties, and convert those strings to functions like so:
for (var prop in parsedObj)
{
if (parsedObj.hasOwnProperty(prop) && parsedObj[prop].match(/^func\=\>/))
{
parsedObj[prop] = new Function(parsedObj[prop].replace('func=>',''));
}
}
Though, seriously, I'd say you might want to rethink your approach, this is not what JSON is for. It's unsafe, all JSON strings are eval'ed, after having made sure they contain no harmful code. This approach is creating a loophole/vulnerability that the JSON people worked hard for to seal off.
For your example will this work:
'user.storeproc = function() { callbuyer( user.no);};'
The Var 'user' is the object of the parsed json.
Ps: maybe you have to format user.no, from 123 to 0123
Following JSON extension, "JFON", does transport of functions and array-properties.
JFON uses eval and is intended for case if:
1) your data is from trusted source ( like not-derived from user input or is a code from your own server), and
2) you know there are no undesired side effects with context of "eval"
(it is a context of eval in function "fromJFON", line 127 )
3) it is costly to refactor your app to use "functionless" JSON;
4) JFON is one-day work, so may be needs more testing;
The idea: use selected property name to escape functions and arrays like
in strings when selected character "\" is used to pass \n and \ for itself.
In JFON, name "wrap" is selected to pass functions and itself: "wrap" : { "fun" : ... and "wrap" : { "esc" : ...
demo: http://landkey.org/Sandbox/z/spaceen86/js/btb/tests/jfon.htm
code ( use commit 0.0.86 ):
https://github.com/lancelab/spaceen/blob/master/js/btb/JFON.js
test: github.com/lancelab/spaceen/blob/master/js/btb/tests/jfon.htm
Here is another, "JWON" extension: JSON-comments, here-documents, monkey-patching of JSONs:
github.com/lancelab/Boardspirator/blob/master/diary/play/tp/jwon.js

Convert json object to json string and use it's functions?

I have a json object with a function:
var thread = {
title: "my title",
delete: function() {
alert("deleted");
}
};
thread.delete(); // alerted "deleted"
thread_json = JSON.encode(thread); // convert to json from object
thread_object = JSON.decode(thread_json); // convert to object from json
thread_object.delete(); // this didn't work
After I converted it back from json string to object, I could not use delete() function.
When you convert something to json, the functions are gone?
Are there ways to keep them in the json string?
I'm using Mootools.
You got it. Take a look at that JSON.encode output. Only simple data types are allowed in JSON representations, partly for ease of creation, and partly for security. (The reason we use something like JSON.decode instead of eval is the possibility of embedding functions.)
You'll have to modify the JSON library source code to accept functions, or write your own in order to preserve the literal definition of the object upon conversion to string.
Consider, though, the possibility that you don't really need to do this. There's probably a better solution, but I can't begin to address that without knowing your exact situation.

Categories