How to convert POST form data to JSON object - javascript

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"}

Related

Javascript: Parse string array into object with custom key names and values

So I have a string which contains a list of custom http headers that is in the following format:
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
I split that up using the pipe as a delimiter:
var splitHeaders = headers.split("|");
I'm left with an array which I can loop through, and I'm trying to convert that string array into an object. This is what I have so far:
var customHeaders = {};
for (var i in splitHeaders) {
var data = splitHeaders[i].split("=");
customHeaders[data[0]] = data[1];
}
What I'm essentially trying to create is an object called customHeaders to hold values like:
customHeaders = {
"Referer":"https://someurl.com/",
"User-Agent":"Some Browser"
};
Am I doing something wrong?
You are on the right track. Use a more standard form of the for loop using the length of the splitHeaders as a limiter:
for (var i = 0; i < splitHeaders.length; i++) {
Working example:
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
var splitHeaders = headers.split('|');
var customHeaders = {};
for (var i = 0; i < splitHeaders.length; i++) {
var data = splitHeaders[i].split("=");
customHeaders[data[0]] = data[1];
}
console.log(customHeaders);
There are also other methods you can use that allow you to convert an array of items into an object, using such as reduce.
var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
headers = headers
.split('|')
.reduce(function(obj, val) {
var split = val.split('=');
obj[split[0]] = split[1];
return obj;
}, {});
console.log(headers);

Convert object from localstorage into text

I am outputting objects from a localstorage and I get:
"[{\"title\":\"q\",\"ingredients\":\"s\",\"instructions\":\"d\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery3110052397224993886441\":{\"display\":\"\"}}},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311079670549304635711\":{\"display\":\"\"}}},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311016424488798697091\":{\"display\":\"\"}},\"salutation\":\"polish\"},{\"title\":\"q\",\"ingredients\":\"q\",\"instructions\":\"a\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311067483883379310751\":{\"display\":\"\"}},\"salutation\":\"italian\"},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery3110317360085863979571\":{\"display\":\"\"}},\"salutation\":\"polish\"}]"
However I want to get rid of all the brackets and only have the actual text so instead of
{\"title\":\"q\"
I want q on the page.
var salt;
$("#salutation").change(function() {
salt = $(this).children(":selected").attr("id");
});
var existingData = JSON.stringify(localStorage.getItem("key")) || [];
document.getElementById("qq").innerHTML +=(existingData);
$('form').submit(function() {
var newArray = [];
$(".add_id2").each(function(){
newArray.push($(this).val());
});
var newArray2 = [];
$(".add_id").each(function(){
newArray2.push($(this).val());
});
var existingData = JSON.parse(localStorage.getItem("key")) || [];
var newData = {
'title': $("#title").val(),
'ingredients': $("#ingredients").val(),
'instructions': $("#inst").val(),
'moreingredients': newArray,
'moreinstruction': newArray2,
'img': img,
'salutation': salt,
};
existingData.push(newData);
localStorage.setItem("key", JSON.stringify(existingData));
Values from localStorage are always stored as strings. You need to use JSON.parse() to convert he string into a valid object, then you can use a for loop to iterate over the json to get the title using json[i].title:
var json = "[{\"title\":\"q\",\"ingredients\":\"s\",\"instructions\":\"d\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery3110052397224993886441\":{\"display\":\"\"}}},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311079670549304635711\":{\"display\":\"\"}}},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311016424488798697091\":{\"display\":\"\"}},\"salutation\":\"polish\"},{\"title\":\"q\",\"ingredients\":\"q\",\"instructions\":\"a\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery311067483883379310751\":{\"display\":\"\"}},\"salutation\":\"italian\"},{\"title\":\"q\",\"ingredients\":\"w\",\"instructions\":\"e\",\"moreingredients\":[],\"moreinstruction\":[],\"img\":{\"jQuery3110317360085863979571\":{\"display\":\"\"}},\"salutation\":\"polish\"}]";
json = JSON.parse(json);
console.log(json);
for (var i = 0; i < Object.keys(json).length; i++) {
console.log("Title is: " + json[i].title);
}

Jquery get window.location.search tag in array

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

Accessing values from the url using JavaScript [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
I just need to get the value of idi variable from the url.
Everything works fine in the below code except splitting "&".
Example: if this is the url: www.site.com/page?idi=22&selse=88
i want to get the idi parameter's value from the url and print it as a value of a hidden text input field.
<script>
q=window.location.search.substring(1);
idi="idi";
sq=q.split("&");
l=sq.length;
for(i=0;i<=l;i++)
{
qv=sq[i].split("=");
if(qv[0]==idi)
{
qvr=qv[1].Split('&');
document.write(<input type='text' value='"+qvr[0]+"' name='get-idi'/>");
break;
}
}
</script>
Improve or help me form a script for this. Thank you!
Try this,
function getUrlParams(url, key) {
var vars = [], hash;
var hashes = url.slice(url.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[key];
}
alert(getUrlParams("www.site.com/page?idi=22&selse=88", "idi"));
Demo: http://jsfiddle.net/EscBg/
Or you can use https://github.com/allmarkedup/jQuery-URL-Parser
The JQuery plugin do the same job, for example to retrieve the value of idi query string param, you can use
$.url().param('idi');
Update: if you want to use window.location.href try this
function getUrlParams(key) {
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[key];
}
This should work fine
var GET = function(key){
var str = window.location.search.substr(1);
var array = str.split('&');
var map = {};
for (var i = 0; i < array.length; ++i) {
var temp = array[i].split('=');
map[temp[0]] = decodeURIComponent(temp[1]);
}
delete map[''];
return (key !== undefined)? map[key] : map;
}
Here, this should help you out:
function getParams(url) {
var result = {}
, params = /[?&]([^?&=]+)=([^?&]+)?/g;
decodeURIComponent(url).replace(params, function(_,key,val) {
result[key] = isNaN(val) ? val : +val;
});
return result;
}
console.log(getParams('www.site.com/page?idi=22&selse=88'));
//^= {idi: 22, selse: 88}
If you're only trying to get one particular value idi as you indicate, then you can use a simple regular expression:
if ((match = window.location.match(/[?&]idi=(\d+)/)) != null){
alert('IDI: ' + match[1]);
}
The regular expression captures any digits after idi= into match[1]

How to extract relative URL from argument values from request string?

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

Categories

Resources