Convert Javascript serialize to Javascript object - javascript

I have a textarea with an id of 'dataArrayField' which has code in it, example:
item1: {
type: 'foo',
fieldName: 'bar'}
},
item2: {
type: 'cat',
fieldName: 'dog'
}
I then run var content = $('#dataArrayField').serialize(); on this textarea, which has a nem of codeformat, so the returned data would be something like:
codeFormat=item1%3a+ etc etc
I then use the $.deparam(content) Javascript plugin to turn the serialized string to an
object.
This works, however, the only key that actually is returned, is the codeFormat name, then the value is the text in the field above, so I get something like this:
What can I do so that I can access all the information in the passed object!

If you have a string which represents a javascript object and want to create an actual object from that, one option would be to use eval.
var str = "item1: {type: 'foo',fieldName: 'bar'},item2: {type: 'cat',fieldName: 'dog'}";
var obj = eval('({' + str + '})');
alert(obj.item1.type); // foo!
If a user can enter text that is later displayed to other users, this is probably not a very secure thing to do.

You can either put a valid JSON string in the textarea such as
{"item1":{"type":"foo","fieldName":"bar"},"item2":{"type":"cat","fieldName":"dog"}}
or you can use regular expressions as in THIS WORKING DEMO to clean it up before applying JSON.parse(). As #jibsales has already pointed out, do not use eval():
$(function() {
var val = $('#dataArrayField').val().replace(/[\s']/g,'').replace(/(\w+)/g,'"$1"');
val = '{' + val.replace(/\}\},/g,'},') + '}';
console.log( JSON.parse(val) );
});

Eval is evil. Consider using JSON.serialize() and JSON.parse() instead. The objects entered in the text area will have to be valid JSON but it is much more secure.

Related

How can I make this JSON.stringify work properly

I have a small issue to make my arrays into the json I want to. I have made this code:
var arrData = [{label:Test,value:199.12}, {label:Test2,value:1024}]
var data = [];
for (var i = 0; i < arrData.length; i++) {
data.push(JSON.stringify({
label: arrData[i][2],
value: arrData[i][3]
}).replace(/\"/g, "").replace("\\r", ""))
}
It also does the job properly. But I do want it to be in this format:
{ label: 'Food', value: 90 },
I want to have the ' ' on the label data and I want to remove the double "" punctuation mark outside the json. Since my current json looks like this:
"{label:Test,value:199.12}", "{label:Test2,value:1024}",
{ label: 'Food', value: 90 } isn't valid JSON so you cannot create it using JSON.stringify.
It isn't any standard serialisation format (although it is a valid JavaScript literal) so if you want to serialise data to it, you'll need to write a custom serialiser.
You could loop over the properties of the object and append them, the associated values, and whatever quotes and commas your format demands, to a string.

Get first word of string inside array - from return REST

I try get the sessionid before REST function, but in the case if I does not convert toString(); show only numbers (21 22 2e ...).
See this image:
1º:
Obs.: Before using split.
!!xxxxxxx.xxxxx.xxxxxxx.rest.schema.xxxxResp {error: null, sessionID: qdaxxxxxxxxxxxxxj}
My code:
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxxxxx","password":"xxxxxxxx","platform":"xxxxx" },
headers: { "Content-Type": "application/json" }
};
client.registerMethod("postMethod", "xxxxxxxxxxx/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data); all return, image 1
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8'); // if i does not convert to string, return numbers, see image 1..
console.log(data); //all inside image 2, and i want just value from sessionid
var output = data;
var res = output.split(" "); // using split
res = res[4].split("}", 1);
}
console.log(res); //image 3
});
I tested with JSON.parse and JSON.stringify and it did not work, show just 'undefined' for all. After convert toString();, And since I've turned the values ​​into string, I thought of using split to get only the value of sessionid.
And when I used split, all transform to array and the return is from console.log(data), see image 2:
2º:
Obs.: After use split and convert to array automatically.
And the return after use split is with the conditions inside my code:
3º:
And the return after use split is with the conditions inside my code:
[ 'bkkRQxxxxxxxxxxxxx' ]
And I want just:
bkkRQxxxxxxxxxxxxx
I would like to know how to solve this after all these temptations, but if you have another way of getting the sessionid, I'd be happy to know.
Thanks advance!
After converting the Buffer to a string, remove anything attached to the front with using data.substr(data.indexOf('{')), then JSON.parse() the rest. Then you can just use the object to get the sessionID.
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
data = data.substr(data.indexOf('{'));
obj = JSON.parse(data);
console.log(obj.sessionID);
}
EDIT:
The issue you are having with JSON.parse() is because what is being returned is not actually JSON. The JSON spec requires the properties to be quoted ("). See this article
If the string looked like this, it would work: {"error": null, "sessionID": qdaxxxxxxxxxxxxxj}
Because the json is not really json, you can use a regular expression to get the info you want. This should get it for you.
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
console.log(match[2]);
EDIT 2: After fully reading the article that I linked above (oops haha), this is a more preferable way to deal with unquoted JSON.
var crappyJSON = '{ somePropertyWithoutQuotes: "theValue!" }';
var fixedJSON = crappyJSON.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
var aNiceObject = JSON.parse(fixedJSON);

How can I use underscore in name of dynamic object variable

Website that I'm making is in two different languages each data is saved in mongodb with prefix _nl or _en
With a url I need to be able to set up language like that:
http://localhost/en/This-Is-English-Head/This-Is-English-Sub
My code look like that:
var headPage = req.params.headPage;
var subPage = req.params.subPage;
var slug = 'name';
var slugSub = 'subPages.slug_en';
var myObject = {};
myObject[slugSub] = subPage;
myObject[slug] = headPage;
console.log(myObject);
Site.find(myObject,
function (err, pages) {
var Pages = {};
pages.forEach(function (page) {
Pages[page._id] = page;
});
console.log(Pages);
});
After console.log it I get following:
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Is you can see objectname subPages.slug_en is seen as a String insteed of object name..
I know that javascript does not support underscores(I guess?) but I'm still looking for a fix, otherwise i'll be forced to change all underscores in my db to different character...
Edit:
The final result of console.log need to be:
{ subPages.slug_en: 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Insteed of :
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Otherwise it does not work
The reason you are seeing 'subPages.slug_en' (with string quotes) is because of the . in the object key, not the underscore.
Underscores are definitely supported in object keys without quoting.
Using subPages.slug_en (without string quotes) would require you to have an object as follows:
{ subPages: {slug_en: 'This-Is-English-Sub'},
name: 'This-Is-English-Head' }
Which you could set with the following:
myObject['subPages']['slug_en'] = subPage;
Or simply:
myObject.subPages.slug_en = subPage;

set array as value in json format in Javascript

I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("test1#test.com");
json_data.links.push("test2#test.com");
json_data.links.push("test3#test.com");
You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will become JSON Literal - a key value pair.
Second thing, You have missed commas after 'name':'Testing' and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
}
In addition to push as mentioned by #giovannilobitos you can use concat and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more complete list of how to modify arrays in JavaScript.

Send JSON with unusual keys

I've object in js with keys-selectors:
{
"[data-index="0"]": {
// something
},
"> .class > .one": {
key: "very bad+ \"\' string"
}
}
How send this object via ajax without any changes in the keys and with correct values?
By correct values I mean that "very bad+ \"\' string" should be total escaped, but save all chars and signs to store in Database.
PS. I know that i can send objects via AJAX
JSON.stringify will transform your object into a JSON string. It can handle special characeters, don't worry.
var json = JSON.stringify(myObject);
When you modify your object a bit
var obj = {
"[data-index='0']": {
// something
},
"> .class > .one": {
key: "very bad+ \"\' string"
}
}
then a JSON.stringify(obj) works. The second pair of " after data-index= provokes an error.
-- edited syntax

Categories

Resources