Is it possible to encode javascript object to javascript(rather than json)? - javascript

I know it is possible to convert a JavaScript data object to JSON using JSON.stringify. e.g:
var cat = {
soundString: 'Meow!'
};
Then call JSON.stringify(cat) to get "{"soundString":"Meow!"}"
I am interested to know if it is possible to have a parallel to this, except instead of turning the JavaScript object into JSON, turn it into a JavaScript string that can be evaluated back to the object.
var cat = {
meow: function() {
console.log('Meow!');
}
};
I want something that would take the cat object and produce a string "{meow: function(){console.log('Meow!');}}", which can be parsed back using eval.
Can this be accomplished?

Write a recursive deep copy method and check for Array.isArray(item)
Use .hasOwnProperty to avoid the prototype chain
Put additional quotations wherever you want
var str = "{"
for (var key in cat) {
str += key + ":" + cat[key] + ","
}
str = str.substr(0, str.length-1) + "}"

Related

Javascript - Store variable as object and function

I've seen instances of a variable being both an object and a string. Example:
alert(x + ""); // Hello
alert(x()); // World
This kind of thing is what jQuery does with the $ variable.
How might you get this effect?
No, a variable can't be both an object and a (primitive) string.
However, if you attempt to convert an object to a string (e.g. using obj + ''), the string returned by its toString method is used instead.
function x() {
return "World";
}
x.toString = function() {
return "Hello";
};

Javascript String Object V.S. just string

OK, first, i'm not going to seek a method to convert the Object to String.
but i'm facing a problem like this:
String.prototype.foo = function() {
return this;
};
var rawString = "abcde";
var fooString = "abcde".foo();
console.log(typeof(rawString) + ': ', rawString);
console.log(typeof(fooString) + ': ', fooString);
or jsfiddle you preferred.
also, a screenshot is attached:
as you can see, i did almost nothing in the prototype method foo, i just return this.
but the result of typeof are totally different
Why is this? how can i just return abcde rather thant {0: "a"...} ?
Thanks!
The this references the String Object, so you need to return it like
return this.toString();
which in turn, creates the primitive string version and returns it.

Finding value in json string

Below is what I have as JSON String.
{
"ID_A0001":{"areaID":"A0001","shopID":"SH004","quantity":14},
"ROW_INFO":{"areaID":"VARCHAR","shopID":"VARCHAR","quantity":"INT"},
"ID_A0002":{"areaID":"A0002","shopID":"SH008","quantity":18}
}
What I want is to get the JSONObject which have ID as ID_A i.e. ID_A0001 & ID_A0002.
I was thinking of using jsonObject.getString("ID_A"), but that is not possible. Could someone tell me what should I do so that I will get as below output.
{
"ID_A0001":{"areaID":"A0001","shopID":"SH004","quantity":14},
"ID_A0002":{"areaID":"A0002","shopID":"SH008","quantity":18}
}
The following code does what you want, assuming the object you posted is stored in obj. In case you actually have a JSON string instead of an object, use JSON.parse() to convert the string to a JavaScript object.
var obj2 = {};
for(var key in obj) {
if(key.substr(0, 4) == 'ID_A') {
obj2[key] = obj[key];
}
}
In the json object you have mentioned, you can modifiy it as follows.
var jsontest={
ID_A0001:{"areaID":"A0001","shopID":"SH004","quantity":14},
ROW_INFO:{"areaID":"VARCHAR","shopID":"VARCHAR","quantity":"INT"},
ID_A0002:{"areaID":"A0002","shopID":"SH008","quantity":18}
};
for(var key in jsontest) {
if(key.substring(0,4)=='ID_A')
alert('key: ' + key + '\n' + 'value: ' + jsontest[key].areaID);
}
http://jsfiddle.net/FBLvP/
Here is a useful link which shows us how to get the list of keys from a json object
http://encosia.com/using-jquery-1-6-to-find-an-array-of-an-objects-keys/1

ask for a method in javascript prototype

i have one question, i have this class in javascript:
//FactVal
UTIL.Classes.FactVal = function(entity, attribute, value) {
this.entity = entity;
this.attribute = attribute;
this.value = value;
}
UTIL.Classes.FactVal.prototype.setEntity = function(entity) {
this.entity = entity;
}
When im serializing a json string to an object of this type, i want to ask if exists the setEntity method, i have this json:
"FactVal": {
"entity": {
"string": "blabla"
}
}
When i read "entity" i want to know if exists a method "setEntity" in the FactVal class, i think i have to do this: the value of 'i' is "FactVal" and the value of 'j' is "entity".
if(UTIL.Classes[i].("set" + j[0].toUpperCase() + j.substring(1,j.length)))
and dont work, how can i do it?
Thanks.
You're close, you want [] and you need to look at the prototype property of the constructor function, not the constructor function itself:
if(UTIL.Classes[i].prototype["set" + j.charAt(0).toUpperCase() + j.substring(1,j.length)])
(I also replaced your j[0] with j.charAt(0), not all JavaScript engines in the wild support indexing into strings like that yet.)
Or better:
if(typeof UTIL.Classes[i].prototype["set" + j.charAt(0).toUpperCase() + j.substring(1,j.length)] === "function")
That works because you can access the property of an object either via the familiar dotted notation with a literal:
x = obj.foo;
...or via bracketed notation with a string:
x = obj["foo"];
// or
s = "foo";
x = obj[s];
// or
p1 = "f";
p2 = "o";
x = obj[p1 + p2 + p2];
Instead of
FactVal.setEntity
You have to look at the prototype, just like you did when setting the property originally:
Factval.prototype.setEntity
also, you need to use bracket notation istead of parenthesis (like you did with the [i]):
if( UTIL.Classes[i].prototype["set" + j[0].toUpperCase() + j.substring(1,j.length)] )
You need to use indexer notation:
if (typeof URIL.Classes[i]["set" + (...)] === "function")
Your question looks like this :
Turning JSON strings into objects with methods
However, that line :
if(UTIL.Classes[i].("set" + j[0].toUpperCase() + j.substring(1,j.length)))
Should be replaced with :
if(typeof UTIL.Classes[i]["set" + j[0].toUpperCase() + j.substr(1)] === "function")
NOTE : j.substr(1) is equivalent to j.substring(1,j.length)

How to get the value of key a and 'a' in javascript

How to get the value of key a and 'a' in javascript?
var obj = {a:1,'a':2}
The first key a will be overwritten by the second 'a'.
obj.a will return 2.
If your key name is a valid Javascript identifier or a number, Javascript will allow you to omit the quotes in key names. In practice, however, it's probably better to train yourself to always use quotes, to avoid confusion like this, and also because JSON requires them.
You can't - they are same key, and that initialiser will create an object with a single element 'a' with value '2'. Try this:
var obj = {a:1,'a':2};
for ( var i in obj )
{
alert(i + '=' + obj[i] );
}
And you'll just get "a=2' in response.
obviously, 'a' is the one-character string with a lowercase a as content; but what do you expect to be the other key? if you want it to be the value of a variable called a, then the curly braces syntax won't help you. Unlike Python, this syntax assumes the keys are strings, and quotes are optional.
You'd have to do something like this:
var a = 'givenkey'
var obj = {}
obj[a] = 1
obj['a'] = 2
this would create an object equivalent to:
var obj = {'givenkey':1, 'a':2}
If you not sure about key - use iteration
for(var k in obj)
alert(k + "=" + obj[k])
When you know key exact value use obj[k]
There isn't any difference.
alert([
obj.a,
obj['a']
].join("\n")); // returns 2 in both cases

Categories