jQuery parseJSON and functions inside the json string - javascript

I'm trying the following:
var objJson = jQuery.parseJSON('"myFunc": function(){ ... }');
This fails. Now my question(s): Why does it fail and how can I achieve what I'm trying?
Thank you in advance!

You seem to have a misconception about what JSON is. JSON is a simple data format with a syntax that resembles JavaScript objects. It's so simple that spec fits a single page. If you have functions it it, it isn't JSON. Thus there is no point in using JSON tools.
Now, the usual way to inject external JavaScript code into an HTML document is the <script> tag:
<script type="text/javascript" src="/path/to/code.js">

ok, the following worked for me (should have googled a bit longer):
var o = eval('(' + '"myFunc": function(){ ... }' + ')')

Related

Why declaring a simple JSON object into a JavaScript script executed into Rhino is not working?

I am not so into JavaScript. I am using JavaScript to develop a litle script working on a JSON document. This JavaScript script is not executed into the browser but ino another product that allow to use JavaScript to script some tasks (the prodcut is WSO2 ESB but it is not important at this time).
This product (WSO2 ESB) uses Rhino as JavaScript engine, used to implement JavaScript scripts into Java application.
I have some problem trying to create a simple JSON object in this kind of environment.
I have done something like this (into my WSO2 ESB code):
<script language="js">
<![CDATA[
var response = JSON.parse(`
{
"forecast": []
}
`);
]]>
</script>
Using the same code into a classic JavaScript file performed into the broswer it works fine but it seems that it can't work using Rhino. I obtain error relating an illegal character (I also tryied to replace the ` and ` with " and " and with ' and ' but I still obtain error).
Something like this in the Java Stacktrace:
Caused by: javax.script.ScriptException: org.mozilla.javascript.EvaluatorException: illegal character (<Unknown Source>#9)
at com.sun.phobos.script.javascript.RhinoScriptEngine.compile(RhinoScriptEngine.java:341)
at com.sun.phobos.script.javascript.RhinoScriptEngine.compile(RhinoScriptEngine.java:323)
at org.apache.synapse.mediators.bsf.ScriptMediator.initInlineScript(ScriptMediator.java:399)
... 32 more
What could be the problem with Rhino? I think that the problem could be related to the `` character that maybe have to be escaped in some way. Some idea?
Or another something more pure JavaScript workaround solution could be: is it possible declare a JSON object like this:
{
"forecast": []
}
in a different way? I mean in a programmatically way without explicitly declare it.
This works in modern browsers that support ES6 with template literals:
var response = JSON.parse(`{"forecast": []}`);
Why, because JavaScript solves the back ticks first as a template and fills them with the content of the variables before the JSON string is parsed:
var test = "Cloudy";
var string = `{\"forecast": ["${test}"]}`;
var response = JSON.parse(string);
console.log(response);
But maybe your Rhino build has no ES6 support, so that won't work. Also the multiline is causing problems:
var response = JSON.parse(''+
'{'+
' "forecast": []'+
'}'
);
console.log(response);

Why use JSON.parse(decodeURIComponent(staticString))?

Certain dynamic web frameworks use this code fragment
<script>
appSettings = JSON.parse(
decodeURIComponent(
"%7B%22setting1%22%3A%22foo%22%2C%22setting2%22%3A123%7D"));
</script>
Is there a standard HTML5/JavaScript problem are they trying to solve with this code. Why not just
<script>
appSettings = {"setting1":"foo","setting2":123};
</script>
Note: this is dynamically generated code. I'm assuming on the server they are doing something like
var settingsString = encodeURIComponent(JSON.stringify(settings));
var output = '<script>appSettings=JSON.parse(decodeURIComponent("' +
settingsString +
'"));</script>';
But it seems like it would work just as well like this
var settingsString = JSON.stringify(settings);
var output = '<script>appSettings=' +
settingsString +
';</script>';
One idea is the latter could contain code but they are the ones providing the string, it's not user data so they're no chance it could be code. Plus using JSON.stringify on the server would remove all code. On the client even then a simple JSON.parse of a JSON.stringifyied object would prevent code.
Is there a concrete problem being solved by the triple parsing? Once by JavaScript, once by decodeURIComponent, once by JSON.parse?
THIS IS NOT AN OPINION BASED QUESTION
The question is what problem is being solved. Either there is a problem being solved or there is not. No opinions required to answer that question. For example if JSON.stringify happens to emit unparseable code sometimes (which as far I know it doesn't but if someone knows better then that would be a good answer as to why).
Also note: I'm not asking why their framework does this. I'm asking if there is real problem being solved in standard HTML5/JavaScript. In other words, should I adopt this pattern because I'm going to run into an issue someday if I don't.
Is there a concrete problem being solved by the triple parsing?
Yes. Your suggested solution has two problems:
It's parsed as HTML. Things like </script> can cause havoc in an inline script.
It's parsed as JS. Not all JSON strings are valid JS literals.
The decodeURIComponent + JSON.parse approach is a crude workaround however and looks more like a quick fix than a proper solution.
#katspaugh is correct
Testing
var settingString = JSON.stringify({
"</script>": "<script>bar=123</script>",
});
Generates the code for the above example as
<script>
appSettings = {"</script>":"<script>window.bar=123</script>"}
</script>
Which fails to parse as HTML. Adding the encodeURIComponent on the server JSON.parse(decodeURIComponent(...)) on the client fixes that issue
DO NOT USE IT.
let str = `C:\\Users\\Administrator\\Desktop\\小灶\\GT4T_translated_Chinese Simplified (简体中文)\\2013\%2F193461.pdf`
let newStr = decodeURIComponent(JSON.parse(`"${str}"`))
Depending on the str content, you may get unexpected errors. The code above will cause this error:
SyntaxError: Unexpected token U in JSON at position 4

how do I convert a querystring into a json object in jquery

This seems like a no brainer but surely there is either an internal js method or a jquery one to take a string like:
intTime=1324443870&fltOriginalAmount=0.00&strOriginalCurrency=GBP
...then a lot more vals and turn it into a JSON object?
I had a dig around this site and google and surprisingly drew blanks...
Anyone got an easy way to do this?
jQuery BBQ does exactly this. See $.deparam, "The opposite of jQuery.param, pretty much."
> var obj = $.deparam('intTime=1324443870&fltOriginalAmount=0.00&strOriginalCurrency=GBP')
> JSON.stringify(obj)
'{"intTime":"1324443870","fltOriginalAmount":"0.00","strOriginalCurrency":"GBP"}'
i used this hack...
$.parseJSON('{"' + qs.replace(/&/g, '","').replace(/=/g, '":"') + '"}');
demo here http://jsbin.com/niqaw/

Fastest way to parse a json strings (without jquery)

can someone tell me the fastest way to parse a json string to an object without jquery?
I want to parse the json string in a script tag before jquery is loaded.
Thanks in advance!
Peter
Use JSON JS
To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.
var myObject = eval('(' + myJSONtext + ')');
taken from http://www.json.org/js.html
var myObject = eval('(' + myJSONtext + ')');
If the JSON string comes from the server you can try the JSONP technique. The JSON is parsed natively in the browser(fast) when loaded and without any library.
eg: if you response is {"name":"Peter"}
A JSONP response will be something like:yourFunction({"name":"Peter"})
yourFunction must be a globally defined function in the page that will receive the call, like:
function yourFunction(json){
//do something with the JSON
}

Yet i'm finding difficult to understand JSON

hey guys, i have read This post, so what i got is JSON is the easiest way to translate a JavaScript object into a PHP/C# associative array or object (and vice-versa).
Now my question is what is goin' on in below code,i.e without JSON/XML i'm still can access my C# object in Javascript, may be i'm wrong, if so Please correct me:
C#
Foreach(DataRow dr in dvItems.Table.Rows) //dvItems is a DataView
{
strItems &= "'" & dr("ItemTitle") & "'," //strItems is a String
}
strItems = strItems.Trim(",")
Javascript : here i'm using Autocomplete.js using JQuery
function InitAutocomplete()
{
data = [<%=strItems %>].sort();
AutoComplete_Create('<%=txtItem.ClientId %>', data);
}
See i'm using strItems in javascript with servertag, so where exactly the JSON is used ? is .net doin' something internally ? i'm totally confused how JSON/XML is used to data passing ?
While you can pass data like this without using JSON, it doesn't ensure that all of the data is safe to pass, e.g. embedded </script> tags. Using JSON will encode your data in a way that prevents this, and you decode it on the JavaScript side with e.g. json2.js.
You're not really using JSON in anything here. You're merely generating an array of strings for javascript and use it in a vvery straightforward manner.
If you wish to transform the JSON to javascript object(s) you need to modify your program and you need a JSON parser. There are several implementations of JSON-parsers, but you mentioned jQuery so you could use: http://api.jquery.com/jQuery.parseJSON/
Parsing with jQuery, however, requires your JSON to be strictly formatted (from v1.4). See http://json.org/ about the correct form. Basically in your situation you should put double quotes around your strings and put the whole array inside square brackets.
Your results should be something like this:
strItems = '['
Foreach(DataRow dr in dvItems.Table.Rows) //dvItems is a DataView
{
// TODO: Escape dr("ItemTitle") so it conforms to http://json.org/ => String
strItems &= "\"" & dr("ItemTitle") & "\"," //strItems is a String
}
strItems = strItems.Trim(",")
strItems &= ']'
<script type="text/javascript">
var jsonArr = <%=strItems%>;
var data = jQuery.parseJSON(jsonArr);
AutoComplete_Create('<%=txtItem.ClientId %>', data);
</script>

Categories

Resources