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

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/

Related

javascript window.open url + json var

What I am trying to accomplish is to open a url(base) with an added var at the end.
window.open(https://vipparcel.com/package/detailed/ + json.id[0])
This was written by someone else to just display an image but I need it to pop more detailed info.
I DO NOT know javascript so its like a child poking at a dead animal here.
I have exhausted my normal go to's and then some to find more info on this.
the url would look like https://vipparcel.com/package/detailed/000000 if the info passes correctly.
Anything pointing me in the right direction would be extremely helpful!
Thank you in advanced.
Try this :
var myurl = "https://vipparcel.com/package/detailed/" + json.id[0];
window.open(myurl);
What errors are you getting? Looks like you're just missing quotations. If that's not the case, is json an object with an array of ids? If instead it's an array of objects with an id property, the following should work:
window.open('https://vipparcel.com/package/detailed/' + json[0].id)
It should look like this:
window.open('https://vipparcel.com/package/detailed/' + json.id[0]);
it's looking for a string to open the website by. You weren't passing a string through to it.

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 to Split many Strings with Jquery

Let's say I have a bunch of strings which I get from user input. Each strings starts with a new line like the following example:
gordon:davis
harley:vona
empir:domen
furno:shyko
I would like to write a function in jQuery which loads the user data from the form and splits each row's sting. However I would ONLY need the first part of the strings, like:
gordon
harley
empir
furno
Is there any simple solution for this?
I have found something called: $.each(split) but I didn't get it work.
I'm sorry I'm a really newbie in Jquery, I hope you guys can help me out! Thanks in advance!
Use String.prototype.split method.
"gordon:davis".split(":") will return ["gordon","davis"]
Based on this, using Array.prototype.map or a JQuery version :
var strings = ["gordon:davis", "harley:vona"];
var splitStrings = strings.map(function (string) {
return string.split(":")[0];
});

Alternative to jquery tmpl for inline html?

I am currently running into long inline html in my jquery in order to generate long html snippets on the fly.
Example:
var personalMessage = $("<div title='" + chatid + "' class='personalMessage'><div class='personalChatName'>" + fullname + "</div><div class='personalChatDialog'></div></div>")
$ContactsBar.prepend(personalMessage);
I want to add even more html in my personalMessage so i started to think that jquery.tmpl will be perfect for this, but jQuery discontinued it which i dont know why, but is there something new or an alternative that everyone uses now thats better? or is everyone still just using jquery.tmpl?
i came across this one just recently: t.js
however, if your needs are fairly limited you could just extend String with a simple template function:
String.prototype.template = function(obj) {
return this.replace(/\{\{([\w]+)\}\}/g, function(str, prop) {
return obj[prop];
});
};
alert('<div>my name is: {{last}}, {{first}}</div>'.template({first:'John', last:'Smith'}));
check it out
If you're looking for an HTML templating language in Javascript, you might want to look into Mustache.js.
It seems fairly popular.
Hope that helps.

jQuery parseJSON and functions inside the json string

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(){ ... }' + ')')

Categories

Resources