How to use special characters in JSON stringify? - javascript

I am trying to stringify my json code for sending it to MVC controller.
But it does not work when data contains some special characters like greater than > or less than sign <.
Here is Sample code
function demo()
{
debugger
var demo = [];
demo.one = 'one';
demo.two = '<just>'
var treeBinding = JSON.stringify(demo);
$.ajax({
url: '/flow/demo',
type: "GET",
data: { dd: treeBinding },
success: function (res) {
},
error: function (error) {
alert(error)
}
});
}
JSON.stringify returns a blank array in this case.
Can anyone help me to get it worked?

First of all your declaration with array is incorrect.That is supposed to be an object but whatever case you need to check difference between object and array.However I assume that demo is an object with two key/properties which will be sent to server.
So declaration should look like this-
var demo = {};
demo.one = 'one';
demo.two = '<just>';
Then you should use to escape -
var treeBinding = encodeURIComponent(JSON.stringify(demo));

You can try something like this:
function arrayToObjectString(arr) {
var returnSrt = "{";
for (var key in arr) {
returnSrt += "\"" + key + "\" : \"" + arr[key] + "\"";
returnSrt += ","
}
returnSrt = returnSrt.substring(0, returnSrt.length - 1) + "}";
return returnSrt;
}
function main() {
var demo = [];
demo.one = 'one';
demo.two = '<just>'
console.log(JSON.stringify(demo))
var resultStr = arrayToObjectString(demo);
console.log(resultStr)
console.log(JSON.parse(resultStr));
}
main();

Related

adding object key and value to URL Query

I have a function which updates the URL query string. in some scenarios it works fine where i have single key and array of values but when i have multiple keys with array of values it doesn't append it to query string but if I see the object i can see the keys and its value. Following is my function
function Querystring(obj) {
var querystring = "";
// Build the query string
var currentQueryString = parseQueryString();
var newQueryString = "";
var dataCategory = Object.keys(obj)[0];
console.log(dataCategory);
// Set the new value
if (obj[dataCategory] != null) {
currentQueryString[dataCategory] = obj[dataCategory].join(",");
// Loop the keys in currentQueryString and contruct new querystring
Object.keys(currentQueryString).forEach(function (key, index) {
if (index == 0) {
newQueryString += "?" + key + "=" + currentQueryString[key];
} else {
newQueryString += "&" + key + "=" + currentQueryString[key];
}
});
}
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + newQueryString;
window.history.pushState({ path: newurl }, '', newurl);
return newQueryString;
}
This is how i am calling this function
$('.select').change(function () {
var SortOrder = $(this).attr("id");
var SortBy = $(this).data("sortby");
var obj = {};
obj[SortOrder] = $(this).val();
obj[SortBy] = [$('option:selected', this).data("price")];
Querystring(obj);
});
Thanks in advance
You can simply this quite a bit. Try the example below. Ignore the getParser function as it is there just for us to be able to test this code.
function getParser(url) {
var a = document.createElement("a");
a.href = url;
return a;
}
function getUpdatedURL(url, newQueryParams) {
var searchParams = url.search.substring(1).split("&");
var obj = {};
searchParams.forEach(function(param){
var paramParts = param.split("=");
obj[paramParts[0]] = paramParts[1];
});
obj = Object.assign(obj, newQueryParams);
url.search = "?"+Object.keys(obj).map(p => p+"="+obj[p]).join("&");
return url.href;
}
var url = getParser("http://example.com/test/page?blah=abc&test=123");
//Ignore this as this is just for us to be able to test and run this example. You'll pass in the window.location instead of the url variable defined here.
console.log(getUpdatedURL(url, { sortOrder: "1345", sortBy: ["price","other","more"] }));
Writing code for it is quiet easy, but to get the full juices, i recommend using this tiny library:
https://www.npmjs.com/package/query-string
i wrote my own code to build and destruct a query string, but i switched to this one as it gives the full rainbow.
Usage
const queryString = require('query-string');
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
console.log(location.hash);
//=> '#token=bada55cafe'
const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'

how to display json resful data using javascript or jquery

how do i display all content in my data array without repeating my self like i have done below .
// Program guide Rest
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://engrid2media.com/nextt/api/epg/schedule/id/",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("EPG Success");
},
error: function() {
alert('EPG Failed!');
},
}).then(function(data) {
var result = data [0];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
$('.ch-type').append(result.type);
$('.ch-resolution').append(result.resolution);
var result1 = data [1];
console.log(result1);
$('.ch-name1').append(result1.ch_name);
$('.ch-logo1').append(result1.ch_logo);
$('.ch-desc1').append(result1.ch_desc);
$('.ch-genre1').append(result1.ch_genre);
$('.ch-type1').append(result1.type);
$('.ch-resolution1').append(result1.resolution);
var result2 = data [2];
console.log(result2);
$('.ch-name2').append(result2.ch_name);
$('.ch-logo2').append(result2.ch_logo);
$('.ch-desc2').append(result2.ch_desc);
$('.ch-genre2').append(result2.ch_genre);
$('.ch-type2').append(result2.type);
$('.ch-resolution2').append(result2.resolution);
var result3 = data [3];
console.log(result3);
$('.ch-name3').append(result3.ch_name);
$('.ch-logo3').append(result3.ch_logo);
$('.ch-desc3').append(result3.ch_desc);
$('.ch-genre3').append(result3.ch_genre);
$('.ch-type3').append(result3.type);
$('.ch-resolution3').append(result3.resolution);
var result4 = data [4];
console.log(result4);
$('.ch-name4').append(result4.ch_name);
$('.ch-logo4').append(result4.ch_logo);
$('.ch-desc4').append(result4.ch_desc);
$('.ch-genre4').append(result4.ch_genre);
$('.ch-type4').append(result4.type);
$('.ch-resolution4').append(result4.resolution);
var result5 = data [5];
console.log(result5);
$('.ch-name5').append(result5.ch_name);
$('.ch-logo5').append(result5.ch_logo);
$('.ch-desc5').append(result5.ch_desc);
$('.ch-genre5').append(result5.ch_genre);
$('.ch-type5').append(result5.type);
$('.ch-resolution5').append(result5.resolution);
});
});
This works fine , but it will be difficult to display over 20 items from the database with this method since i would have to do it one after the other.
A simple for loop would do it.
.then(function(data) {
for (var i = 0; i < 6; ++i)
{
var prefix = (i == 0 ? "" : i.toString());
$('.ch-name' + prefix).append(data[i].ch_name);
$('.ch-logo' + prefix).append(data[i].ch_logo);
$('.ch-desc' + prefix).append(data[i].ch_desc);
$('.ch-genre' + prefix).append(data[i].ch_genre);
$('.ch-type' + prefix).append(data[i].type);
$('.ch-resolution' + prefix).append(data[i].resolution);
}
});
Why not just write helper function?
Something like that.
function(data) {
var result,
suffix = '';
for (var i in data) {
result = data[i];
if (i > 0) {
suffix = i;
}
$('.ch-name' + suffix).append(result.ch_name);
$('.ch-logo' + suffix).append(result.ch_logo);
$('.ch-desc' + suffix).append(result.ch_desc);
$('.ch-genre' + suffix).append(result.ch_genre);
$('.ch-type' + suffix).append(result.type);
$('.ch-resolution' + suffix).append(result.resolution);
}
}
Try utilizing $.each()
$.each(data, function(key, val) {
var idx = key === 0 ? "" : key;
$(".ch-name" + idx).append(val.ch_name);
$(".ch-logo" + idx).append(val.ch_logo);
$(".ch-desc" + idx).append(val.ch_desc);
$(".ch-genre" + idx).append(val.ch_genre);
$(".ch-type"+ idx).append(val.type);
$(".ch-resolution" + idx).append(val.resolution);
});

javascript, exception for string/object manipulation

So, I have to functions to turn a string to an object and an object to a string, however I need to account for an except and I am not sure how. Let me show you what I have
parseObjectToUrl: function (obj){
var myStr = "";
var first_iteration = true;
for (var p in obj) {
if(first_iteration){
myStr += p + "=";
first_iteration = false;
}else{
myStr += "&" + p + "=";
}
tObj = obj[p];
var first_inner = true;
for(t in tObj){
if(first_inner){
myStr += t;
first_inner = false;
}else{
myStr += "," + t;
}
yObj = tObj[t];
for( y in yObj){
myStr += "/" + yObj[y];
}
}
}
return myStr;
},
parseObjectFromUrl : function(url){
var builtObj = {};
//remove first slash
url = url.slice(0, 0) + url.slice(1);
var ch = url.split('&');
var tempParent = {};
for (var p in ch) {
var tempSub = {};
var arr = ch[p].split('=');
var keyParent = arr[0];
var splitInside = arr[1].split(",");
for (var i in splitInside) {
var sub = splitInside[i].split('/');
var subKey = sub[0];
tempSub[subKey] = sub.slice(1);
}
tempParent[keyParent] = tempSub;
}
return tempParent
}
So these the string looks like
/module1=mod1/2/3/4,mod2/2/3/4&module2=mod2/3/4/5
and the object looks like
myObj =
{
module1 : { mod1 : [2,3,4] , mod2 [2,3,4]} ,
module2 : { mod2 : [3,4,5]}
}
So these functions work fine for me however I (unfortunately) need to be able to handle the case when the user adds an "/" into the options like -
myObj =
{
module1 : { mod1 : [2/,3/,4/] , mod2 [2,3,4]} ,
module2 : { mod2 : [3,4,5]}
}
I'm sure it's going to throw a wrench in my function because i'm splitting by the "/", so I'm not sure how to get around this. Would i escape the slash? How would that fit into the functions if so? Looking for any advice on this issue. Thanks!
Edit:
I was able to encode the escaped url like :
obj.replace(/([/-])/g, "%2F");
to an escaped url, hoever I am having trouble doing the reverse of this. here is my attempt.
obj.replace(/(%2F)/g, "/");
in my opinion it would be better to use url arrays, but keep in mind the characters for your url could be limited:
maximum length of HTTP GET request?
having said that one could do something like this:
module1[]=1&module1[]=2&module2[]=4&module2[]=3
this is equal to the following pseudo code:
$_GET["module1"] = array(1,2);
$_GET["module2"] = array(4,3);
and use encodeURIComponent & decodeURIComponent for your values
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Convert javascript array into a php unserializable string

I need to convert a javascript array into a string readable by php "unserialize".
In my javascript, I have:
var params = {};
params['showTitle'] = 0;
params['class'] = '';
params['ajax'] = 0;
params['ajaxDom'] = '';
params['what'] = 'defi';
params['color'] = 'dark';
The output I really need to get is this :
a:6:{s:9:"showTitle";i:0;s:5:"class";s:0:"";s:4:"ajax";i:0;s:7:"ajaxDom";s:0:"";s:4:"what";s:4:"defi";s:5:"color";s:4:"dark";}
Why do I need this? because the output is red on the server side (with php function unserialize) and I cannot change this (it's part of a framework).
My question is : how to convert the javascript array? I've tried (but didn't work):
params = JSON.stringify(params);
params = $.param(params);
It should be easy but I'm stuck... Thank you !
Please see if u can make use of this
http://phpjs.org/functions/serialize/
Just send that js array to the server as JSON, then parse it with json_decode and serialize it with serialize function. Then you can unserialize it.
This function/answer assumes a lot: mainly that the only two types of data in your JavaScript "array" will be integers and strings, none the less it produces the type of output you demonstrated that the PHP unserialize function requires.
var params = {};
params['showTitle'] = 0;
params['class'] = '';
params['ajax'] = 0;
params['ajaxDom'] = '';
params['what'] = 'defi';
params['color'] = 'dark';
function jsArrToPhpSerializedString( arrObj ) {
var str_parts = ['', '', '}'],
arrLen = 0,
ret = '';
for (var prop in arrObj) {
var val = arrObj[prop];
arrLen += 1;
str_parts[1] += 's:' + prop.length + ':"' + prop + '";';
if (typeof val == 'number') {
str_parts[1] += 'i:' + val + ';';
} else if (typeof arrObj[prop] == 'string') {
val = (!val) ? '""' : '"' + val + '"';
str_parts[1] += 's:' + arrObj[prop].length + ':' + val + ';';
}
}
str_parts[0] = 'a:' + arrLen + ':{';
ret = str_parts.join('');
return ret;
}
console.log( jsArrToPhpSerializedString(params) );
// "a:6:{s:9:"showTitle";i:0;s:5:"class";s:0:"";s:4:"ajax";i:0;s:7:"ajaxDom";s:0:"";s:4:"what";s:4:"defi";s:5:"color";s:4:"dark";}"

Javascript location.search

How could I specifically get every of these query strings in
file:///K:/CKaing_C20_A01_Casino2/game.html?First+Name=Testfirst&Last+Name=Testlast&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000
For example, I want to get Testfirst, and then assign it to a variable so I can use it later on. Same thing with the others.
This is what I have so far to remove all the +, =
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
for (var i=0; i < formArray.length; ++i) {
document.writeln(formArray[i] + "<br />");
}
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/\=/g,"\"\:\"").replace(/\&|(\/\?)/g,"\", \""))+"\"}")
I made that one for a webpage that uses a rare ("/?") separator too.
http://example.com/?a=0&b=bee/?c=third
First one will work for URLs like that
If you want it for a conventional location:
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/\=/g,"\"\:\"").replace(/\&/g,"\", \""))+"\"}")
Once splitSearch is defined you can get "pnum" string like this:
splitSearch.pnum
splitSearch["pnum"]
Another way to get it:
var splitSearch = JSON.parse("{\""+(location.search.substr(1).replace(/(\=)|(\&)|(\/\?)/g, function(k) {
var rtn=k;
if (k == "\=") rtn="\"\:\"";
else if ((k == "\&") /*|| (k == "\/\?")*/) rtn="\",\"";
return rtn;
})+"\"}"))
A mix of use of replace with regEx and the split function does the work.
var str = "file:///K:/CKaing_C20_A01_Casino2/game.html?
First+Name=Testfirst&Last+Name=Testlast
&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000";
var argStrIndex = str.indexOf("?");
var argStr = str.substring(argStrIndex+1);
var args = argStr.replace(/\+/g," ").split("&");
for (var i=0;i<args.length;i++){
alert(args[i]);
}
demo: http://jsfiddle.net/7meAv/
something like that :
var search = location.search
.replace(/^\?/,'')
.replace(/\+/g,' ')
.split('&')
.map(function(string){
var split = string.split('=');
var res={};
res[split[0]]=split[1];
return res;
});
should return
[{"First Name":"Testfirst"},{"Last Name":"Testlast"},{"pnum":"123-456-7890"},{"postCode":"A1A 1A1"},{"startMoney":"5000"}]"
You'd need to take care of url encoding though.
A combination of the two answers already given (jsfiddle: http://jsfiddle.net/russianator/GymEq/)
var url = 'file:///K:/CKaing_C20_A01_Casino2/game.html?First+Name=Testfirst&Last+Name=Testlast&pnum=123-456-7890&postCode=A1A+1A1&startMoney=5000';
queryObject = {};
url.substring(url.indexOf('?')+1)
.replace(/\+/g,' ')
.split('&')
.forEach(function(item) {
splitItem = item.split('=');
queryObject[splitItem[0]] = splitItem[1];
});
Returns an object like this:
{
"First Name": "Testfirst",
"Last Name": "Testlast",
...
}

Categories

Resources