I'm using python-spidermonkey to run JavaScript code.
In order to pass objects (instead of just strings) to Python, I'm thinking of returning a JSON string.
This seems like a common issue, so I wonder whether there are any facilities for this built into either Spidermonkey or python-spidermonkey.
(I do know about uneval but that is not meant to be used for JSON serialization - and I'd rather avoid injecting a block of JavaScript to do this.)
I would use JSON.stringify. It's part of the ECMAScript 5 standard, and it's implemented in the current version of spidermonkey. I don't know if it's in the version used by python-spidermonkey, but if it isn't, you can get a JavaScript implementation from http://www.json.org/js.html.
Related
I am trying to use JSON.parse to parse a string to the array of array, such as
var a = "[['1909-23', 'egg']]"
JSON.parse(a)
It gives me the SytaxError. Wonder if there is any easy way to solve it. Thanks.
The string
"[['1909-23', 'egg']]"
Is not a valid JSON string. As such you can't call JSON.parse() on it.
The JSON format requires double quotes around strings.
A solution would be then to use double quotes:
var a = '[["1909-23", "egg"]]';
console.log(JSON.parse(a));
Before you use this, please read Why is using the JavaScript eval function a bad idea?. This will potentially open up your JavaScript to code injection attacks. A much better solution is to actually turn your string into correct JSON and parse is using JSON.parse
That all said, you can “parse” (actually you've executing the string as javascript, hence the injection problem) this string using eval.
var a = "[['1909-23', 'egg']]"
var b = eval(a);
console.log(b);
Note the warning on MDN
Do not ever use eval!
eval() is a dangerous function, which executes the code it's passed
with the privileges of the caller. If you run eval() with a string
that could be affected by a malicious party, you may end up running
malicious code on the user's machine with the permissions of your
webpage / extension. More importantly, a third-party code can see the
scope in which eval() was invoked, which can lead to possible attacks
in ways to which the similar Function is not susceptible.
eval() is also slower than the alternatives, since it has to invoke
the JS interpreter, while many other constructs are optimized by
modern JS engines.
Additionally, modern javascript interpreters convert javascript to
machine code. This means that any concept of variable naming gets
obliterated. Thus, any use of eval will force the browser to do long
expensive variable name lookups to figure out where the variable
exists in the machine code and set it's value. Additonally, new things
can be introduced to that variable through eval() such as changing the
type of that variable, forcing the browser to reevaluate all of the
generated machine code to compensate. However, there (thankfully)
exists a very good alternative to eval: simply using window.Function.
As an example of how you convert code using evil eval() to using
Function(),
If I'm using javascript (or TypeScript), I can do following (just idea);
object = JSON.parse(jsonString)
And I can just use it like this,
alert(object.property);
Super Simple.
If I'm using Java, I need to create classes and parse it to use it. I understand.
How about Kotlin and Swift. They have optional types, so why single line, Javascript-like simple parsing doesn't exist for them, or does it? (Without even data class or going through JSON's properties)
If you look up what JSON stands for it's no wonder why JavaScript has "native support" for it: JavaScript Object Notation
In Kotlin you'll need to use libraries for parsing JSON, I'd recommend Jackson for that, a library widely used with Java already.
JavaScript does not support operator overloading. Matrix libraries in JavaScript could not simplify notation. I would like to create operator overloading with a simple trick by adding using syntax like z = x++y. This is not a valid statement in JavaScript.
That is why I would like to create an include method which will parse existing JavaScript files and replace those statements with actual JavaScript code. This is somehow related to coffescript where the compiler is inside JavaScript. What would be the best way to approach that.
I have string manipulation solution:
"z=x++y;".replace(/(.*)=(.*)\+\+(.*)/i,"for(var _i_=0;_i_<$1.length;_i_++){ $1[i] = $2[i]+$3[i]}")
Example run:
for(var _i_=0;_i_<c.length;_i_++){ c[i] = data[0][i]+data[1][i];}
Obtaining Matlab, numpy like environment in JavaScript would be very convenient for easily deploying scientific models as web applications and avoiding computational burden in server side. Also, parallelization would be as easy as opening another browser tab from somewhere.
In javascript, I want to use JSON.stringify. But some (older) browsers do not recognize JSON as a defined object. Is there a javascript file that I can include that defines JSON, and all it's awesome functionality, for browsers that do not natively support JSON?
I should note that I'm referring to a specifically defined JSON object, rather than the more general concept of javascript object notation.
Douglas Crockford (the inventor of JSON) provides json2.js, an efficient JSON "parser" that doesn't actually parse JSON; it uses regular expressions to sanitise JSON before passing it to eval, and falls back on native JSON support if the browser has it.
He also provides a more conventional recursive-descent parser and a state-machine-based parser in the same repo.
Quick Question. Eval in JavaScript is unsafe is it not? I have a JSON object as a string and I need to turn it into an actual object so I can obtain the data:
function PopulateSeriesFields(result)
{
data = eval('(' + result + ')');
var myFakeExample = data.exampleType
}
If it helps I am using the $.ajax method from jQuery.
Thanks
Well, safe or not, when you are using jQuery, you're better to use the $.getJSON() method, not $.ajax():
$.getJSON(url, function(data){
alert(data.exampleType);
});
eval() is usually considered safe for JSON parsing when you are only communicating with your own server and especially when you use a good JSON library on server side that guarantees that generated JSON will not contain anything nasty.
Even Douglas Crockford, the author of JSON, said that you shouldn't use eval() anywhere in your code, except for parsing JSON. See the corresponding section in his book JavaScript: The Good Parts
You should use JSON and write JSON.parse.
"Manual" parsing is too slow, so JSON.parse implementation from the library checks stuff and then ends up using eval, so it is still unsafe. But, if you are using a newer browser (IE8 or Firefox), the library code is not actually executed. Instead, native browser support kicks in, and then you are safe.
Read more here and here.
If you can't trust the source, then you're correct...eval is unsafe. It could be used to inject code into your pages.
Check out this link for a safer alternative:
JSON in Javascript
The page explains why eval is unsafe and provides a link to a JSON parser at the bottom of the page.
Unsafe? That depends on if you can trust the data.
If you can trust that the string will be JSON (and won't include, for example, functions) then it is safe.
That said - if you are using jQuery, why are you doing this manually? Use the dataType option to specify that it is JSON and let the library take care of it for you.
If you are using jQuery, as of version 1.4.1 you can use jQuery.parseJSON()
See this answer: Safe json parsing with jquery?
Using JavaScript’s eval is unsafe. Because JSON is just a subset of JavaScript but JavaScript’s eval allows any valid JavaScript.
Use a real JSON parser like the JSON parser from json.org instead.
The alternative to evaluating the code is to parse it manually. It's not as hard as it sounds but it's quite a lot heavier at runtime. You can read about it here.
The important part to note is evaluating JSON is not inherently insecure. As long as you trust the source not to balls things up. That includes making sure that things passed into the JSON encoder are properly escaped (to stop people 2 steps up the stream executing code on your users' machines).
you can try it like this
var object = new Function("return " + jsonString)()
Another great alternative is YUI:
http://yuilibrary.com/yui/docs/json/
So your code would be something like:
Y.JSON.parse('{"id": 15, "name": "something"}');