I have a string similiar to document.cookie:
var str = 'foo=bar, baz=quux';
Converting it into an array is very easy:
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
str[i].split('=');
}
It produces something like this:
[['foo', 'bar'], ['baz', 'quux']]
Converting to an object (which would be more appropriate in this case) is harder.
str = JSON.parse('{' + str.replace('=', ':') + '}');
This produces an object like this, which is invalid:
{foo: bar, baz: quux}
I want an object like this:
{'foo': 'bar', 'baz': 'quux'}
Note: I've used single quotes in my examples, but when posting your code, if you're using JSON.parse(), keep in your mind that it requires double quotes instead of single.
Update
Thanks for everybody. Here's the function I'll use (for future reference):
function str_obj(str) {
str = str.split(', ');
var result = {};
for (var i = 0; i < str.length; i++) {
var cur = str[i].split('=');
result[cur[0]] = cur[1];
}
return result;
}
The shortest way
document.cookie.split('; ').reduce((prev, current) => {
const [name, ...value] = current.split('=');
prev[name] = value.join('=');
return prev;
}, {});
Why exactly do you need JSON.parse in here? Modifying your arrays example
let str = "foo=bar; baz=quux";
str = str.split('; ');
const result = {};
for (let i in str) {
const cur = str[i].split('=');
result[cur[0]] = cur[1];
}
console.log(result);
note : The document.cookie (question headline) is semicolon separated and not comma separated (question) ...
An alternative using reduce :
var str = 'foo=bar; baz=quux';
var obj = str.split(/[;] */).reduce(function(result, pairStr) {
var arr = pairStr.split('=');
if (arr.length === 2) { result[arr[0]] = arr[1]; }
return result;
}, {});
A way to parse cookies using native methods like URLSearchParams and Object.fromEntries, avoiding loops and temporary variables.
Parsing document.cookie:
Object.fromEntries(new URLSearchParams(document.cookie.replace(/; /g, "&")))
For the scope of the question (cookies are separated by , and stored in variable str)
Object.fromEntries(new URLSearchParams(str.replace(/, /g, "&")))
Given an array a containing your intermediate form:
[['foo', 'bar'], ['baz', 'quux']]
then simply:
var obj = {};
for (var i = 0; i < a.length; ++i) {
var tmp = a[i];
obj[tmp[0]] = tmp[1];
}
To convert it to an object, just do that from the beginning:
var obj = {};
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
var tmp = str[i].split('=');
obj[tmp[0]] = tmp[1];
}
Then, if you want JSON out of it:
var jsonString = JSON.stringify(obj);
parse cookies (IE9+):
document.cookie.split('; ').reduce((result, v) => {
const k = v.split('=');
result[k[0]] = k[1];
return result;
}, {})
I'm a fan of John Resig's "Search and don't replace" method for this sort of thing:
var str = 'foo=bar, baz=quux',
arr = [],
res = '{';
str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) {
arr.push('"' + key + '":"' + value + '"');
});
res += arr.join(",") + "}";
alert(res);
Working example: http://jsfiddle.net/cm6MT/.
Makes things a lot simpler without the need for JSON support. Of course, it's just as easy to use the same regular expression with exec() or match().
Whoops, I thought you wanted to convert to a JSON string, not an object. In that case, you only need to modify the code slightly:
var str = 'foo=bar, baz=quux',
res = {};
str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) {
res[key] = value;
});
console.log(res.foo);
//-> "bar"
Working example 2: http://jsfiddle.net/cm6MT/1/
Most of the above solutions fail with the __gads cookie that Google sets because it uses a '=' character in the cookie value.
The solution is to use a regular expression instead of calling split('='):
document.cookie.split(';').reduce((prev, current) => {
const [name, value] = current.split(/\s?(.*?)=(.*)/).splice(1, 2);
prev[name] = value;
return prev;
}, {});
That's pretty crappy data, as long as its not using ,= this would work on that data
var text = 'foo=bar, baz=quux',
pattern = new RegExp(/\b([^=,]+)=([^=,]+)\b/g),
obj = {};
while (match = pattern.exec(text)) obj[match[1]] = match[2];
console.dir(obj);
An alternate version of your updated solution that checks for the null/empty string and just returns an empty object and also allows for custom delimiters.
function stringToObject(str, delimiter) {
var result = {};
if (str && str.length > 0) {
str = str.split(delimiter || ',');
for (var i = 0; i < str.length; i++) {
var cur = str[i].split('=');
result[cur[0]] = cur[1];
}
}
return result;
}
first thing that occurred to me, I'll leave it as the original version, but cookies should not be empty otherwise there will be a json parse error
JSON.parse(`{"${document.cookie.replace(/=/g,'":"').replace(/; /g,'","')}"}`)
fast and reliable version - cookie to object
let c=document.cookie.split('; '),i=c.length,o={};
while(i--){let a=c[i].split('=');o[a[0]]=a[1]}
and short function for get single cookie
getCookie=e=>(e=document.cookie.match(e+'=([^;]+)'),e&&e[1])
function getCookie(){
var o=document.cookie.split("; ");
var r=[{}];
for(var i=0;i<o.length;i++){
r[o[i].split("=")[0]] = o[i].split("=")[1];
}
return r;
}
Just call getCookie() and it will return all cookies from the current website.
If you have a cookie called 'mycookie' you can run getCookie()['mycookie']; and it will return the value of the cookie 'mycookie'.
There is also a One-Line option:
function getCookie(){var o=document.cookie.split("; ");var r=[{}];for(var i=0;i<o.length;i++){r[o[i].split("=")[0]] = o[i].split("=")[1];}return r;}
This one can be used with the same methods as above.
if there any default functions that can convert a post form data string into json object ?
Here is an example
sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true
As you can this is the format of POST form data. I need to convert it into JSON object
{
"sendNotification": "true",
"type": "extended",
"additionalNotes": "",
"returnToMainPage": "true"
}
Also it should handle arrays like this
blog.blogposts[1].comments 1
blog.blogposts[1].likes 12
I wonder how can I do this using existing tools and libraries. I know that I can write my own converter, but I guess there should a default one.
Thanks
IMPORTANT
I don't have a form, I need just convert the form data string.
Try this
var params = getUrlVars('some=params&over=here');
console.log(params);
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
myJson[hash[0]] = hash[1];
}
return myJson;
}
I found it here Convert URL to json
I see it this way
getStringJson('sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true');
function getStringJson(text) {
var json = {}, text = text.split("&");
for (let i in text){
let box = text[i].split("=");
json[box[0]] = box[1];
}
return JSON.stringify(json);
}
Output generated:
"{"sendNotification":"true","type":"extended","additionalNotes":"","returnToMainPage":"true"}"
Working Demo
// Form Data String
var dataString = "sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true";
// Split the String using String.split() method. It will return the array.
var params = dataString.split("&");
// Create the destination object.
var obj = {};
// iterate the splitted String and assign the key and values into the obj.
for (var i in params) {
var keys = params[i].split("=");
obj[keys[0]] = keys[1];
}
console.log(obj); // Object {sendNotification: "true", type: "extended", additionalNotes: "", returnToMainPage: "true"}
Building on the answer from Prashanth Reddy, if you want json string output simply add JSON.stringify(myJson); on the return
var params = getUrlVars('sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true');
console.log(params);
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
myJson[hash[0]] = hash[1];
}
return JSON.stringify(myJson);
}
Output: {"sendNotification":"true","type":"extended","additionalNotes":"","returnToMainPage":"true"}
Let's say i have this address: http://**/test.php?alfa=1&beta=2
I know that i can get ?alfa=1&beta=2 using the search tag in window location.... but is there any way to split the result into 2 strings, in this case, first would be ?alfa=1 and the second one &beta=2 (or just beta=2) using JQuery?
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Not my work. Found it here First hit on Google.
you can use Split method,
sample-
var str = "How are you doing today?";
var n = str.split(" ");
will give you array
How,are,you,doing,today?.
for your problem you can spit text using '?' keyword first and next by '&' key...
there is a plugin jQuery BBQ: http://benalman.com/projects/jquery-bbq-plugin/
You can use the following function, but it returns an object and not an array
var params = $.deparam.querystring();
console.log(params);
Object {alfa: "1", beta: "2"}
URL: //somesite.com/?v1=1&v2=2&v3=3
$(function () {
var in_url = [];
var in_url_str = window.location.search.replace('?','').split('&');
$.each(in_url_str,function (kay,val) {
var v = val.split('=');
in_url[v[0]]=v[1];
});
console.log(in_url);
});
in console
[v1: "1", v2: "2", v3: "3"]
v1:"1"
v2:"2"
v3:"3"
To get a Json object with keys.
JSON.parse('{' + window.location.search.slice(1).split('&').map(x => { y = x.split('='); return '"' + y[0] + '":' + y[1]}).join(',') + '}')
I am looking for an alternative(s) that allow variables to be pulled in from the URL to be used in scripts on the page.
The query string can also be used for this.
Here's a little helper:
var getQueryValue = (function () {
var populated, queryArray = [];
return function (key) {
populated || populate();
return queryArray[key];
}
function populate ()
{
var pair, chunks, l, i = 0, queryString = window.location.href.split('?')[1];
populated = true;
if ( ! queryString ) return;
chunks = queryString.split('&');
l = chunks.length;
for ( ; i < l; i++ ) {
pair = chunks[i].split('=');
queryArray[ pair[0] ] = pair[1];
}
}
}());
Use it as follows:
var page = getQueryValue('page');
I think the best way is to use cookies.
I have a request url / string var like
http://ip_or_url:4773/image_renderer.service?action=resize&from_format=png&from_url=http://ip_or_url:4773/my_file.user.file&to_format=jpg&w=1920&h=1200`
It looks terribly scary. I wonder how to extract the following argument pair from it and then extract relative file_url from that pair value my_file.user.file
from_url=http://195.19.243.13:4773/my_file.user.file ?
With pure javascript. It'll return an array of key/value pairs.
function getUrlParts(url){
// url contains your data.
var qs = url.indexOf("?");
if(qs==-1) return [];
var fr = url.indexOf("#");
var q="";
q = (fr==-1)? url.substr(qs+1) : url.substr(qs+1, fr-qs-1);
var parts=q.split("&");
var vars={};
for(var i=0;i<parts.length; i++){
var p = parts[i].split("=");
vars[unescape(p[0])]= p[1] ? unescape(p[1]):"";
}
// vars contain all the variables in an array.
return vars;
}
Let me know if any of your test cases fails.
When the url is in the varaible sUrl:
var sFromUrl = sUrl.match(/from_url=[^&]*/)[0];
var sBasename = sFromUrl.match(/[^\/]*$/)[0];
Also see this example.
Use this to get your url variables in JS
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
and then string.substring(string.search("/")) to get your piece of string