Let's say I have:
var json = '{"greetings": "`${greetings}`"}';
var obj = JSON.parse(json);
var template = obj.greetings; //`${greetings}`
var greetings = 'hello';
how to evaluate template to get hello ?
Since JSON.parse() returns obj.greetings as string, you can use eval() to run the string as js. So just:
var json = '{"greetings": "`${greetings}`"}';
var obj = JSON.parse(json);
var template = eval(obj.greetings); //`${greetings}`
var greetings = 'hello';
console.log(greetings)// hello
But eval() should always be used with caution as string maybe entered through user input.
Edit:
The above code with eval returns undefined.
This is because JavaScript Hoisting doesn't work for initialized variable.
So we surely need to move the initialisation var greetings = 'hello'; at the top.
Solution without eval():
Apply template string to the whole string.
var greetings = 'hello';
var json = `{"greetings": "${greetings}"}`;
var obj = JSON.parse(json);
var template = obj.greetings; //`${greetings}`
console.log(template); //hello
Related
Here is Code
var str = "Value1";
var str1 = "Value2";
var obj = {
[str]: str1
};
console.log(obj);
I am getting obj as
{
Value1:"Value2"
}
But I want this object as
{
"Value1":"Value 2"
}
Can any one explain how it is possible?
At first your code: var obj = {["Value1"]: "Value2"}; is wrong. You have to write:
var obj = {"Value1": "Value2"}; or var obj = {Value1: "Value2"};.
And then if I understood you correctly: in your comment you wrote:
I wana get Value1 in double quotes too dynamic means I want dynamic index too in double quotes
The answer:
Object {Value1:"Value2"} is the same like {"Value1":"Value2"}. The difference is to see in displaying (spelling, writing) of your code only.
For example you will not see the difference if you execute following code:
var myObj1 = {"Value1":"Value2"};
var myObj2 = {Value1:"Value2"};
console.log(myObj1.Value1); //Value2
console.log(myObj2.Value1); //Value2
console.log(myObj1["Value1"]); //Value2
console.log(myObj2["Value1"]); //Value2
console.log(JSON.stringify(myObj1)); //{"Value1":"Value2"}
console.log(JSON.stringify(myObj2)); //{"Value1":"Value2"}
i used this code in nodejs to get data from json but gets error and say undefined
var obj = {payload:'fp_2'};
var myJSON = JSON.stringify(obj);
console.log(myJSON.payload); //output: undefined
and i have same error in javascript
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var obj = {payload:'fp_2'};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON.payload;
</script>
</body>
</html>
what is my error? can any one help me...
obj is already object, you can
var obj = {payload:'fp_2'};
console.log(myJSON.payload);
to parse string to object use JSON.parse
var str = '{"payload": "fp_2"}';
var myJSON = JSON.parse(str);
console.log(myJSON.payload);
JSON.stringify used to convert obejct to string
var obj = {payload:'fp_2'};
var str = JSON.stringify(obj);
console.log(str);
// {"payload":"fp_2"}
What happens in both your example is you are trying to get property "payload" from a string, which does not have this kind of property.
The method JSON.stringify() creates string from any given object, so your custom object with property "payload" was transformed to JS string object, which does not have it anymore.
This is the list of properties, that JS string has:
constructor
length
prototype
You can find definition of each property and read more about strings in JS with this link: W3 Schools JS string
If you want to use "payload" from your custom object, you don't need to JSON.stringify() it. Just use it:
var obj = {payload:'fp_2'};
console.log(obj.payload);
// Or in your html example
var obj = {payload:'fp_2'};
document.getElementById("demo").innerHTML = obj.payload;
write this for nodejs
var obj = {payload:'fp_2'};
console.log(obj.payload);
write this for script file
<script>
var obj = {payload:'fp_2'};
document.getElementById("demo").innerHTML = obj.payload;
</script>
I have taken a string that is "title:artist" and used str.split :
res = song.split(":");
Which gives me an output of :
["Ruby","Kaiser Chiefs"]
I was wondering how I could add name to this so that it appears as :
["name":"Ruby", "artist":"Kaiser Chiefs"]
var res = song.split(':');
var jsonString = JSON.stringify({ name: res[0], artist: res[1] });
You can find more information about how to use JSON.stringify here but basically what it does is takes a JavaScript object (see how I'm passing the data as an object in my answer) and serializes it into a JSON string.
Be aware that the output is not exactly as you have described in your question. What you have is both invalid JavaScript and invalid JSON. The output that I have provided will look more along the lines of {"name":"Ruby", "artist":"Kaiser Chiefs"}. Notice how there is {} instead of [].
["name":"Ruby", "artist":"Kaiser Chiefs"] isn't a valid format I guess you want to create an object so you could use just the split like :
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {'name': my_string_arr[0],"artist": my_string_arr[1]};
console.log(my_object);
Or also assign the values to the attributes separately like:
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {};
my_object.name = my_string_arr[0];
my_object.artist = my_string_arr[1];
console.log(my_object);
Hope this helps.
What you're looking for is: Object. Here is how you do it:
var str = "Ruby:Kaiser Chiefs";
var res = str.split(':');
// this is how to declare an object
var myObj = {};
// this is one way to assigne to an object
// using: myObj["key"] = value;
myObj["name"] = res[0];
// this is another way to assign to an object
// using: myObj.key = value;
myObj.artist = res[1];
console.log(myObj);
I'm taking charge of a javascript webapp. It's very complex, and I'm having some trouble with syntax:
getThemeBaseUrl = function() {
var customConfigPath = "./customer-configuration";
if (parseQueryString().CustomConfigPath) {
customConfigPath = parseQueryString().CustomConfigPath;
}
var clientId = parseQueryString().ClientId;
return customConfigPath + "/themes/" + clientId;
};
parseQueryString = function() {
var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
while ( m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
};
in particular parseQueryString().CustomConfigPath and the var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
The first seems to be a sort of property access by the parseQueryString function.
The second seems an array declaration, but without the Array() constructor. Also, the m value is recalled without the presumed array result in the while cycle.
By looking at:
parseQueryString().CustomConfigPath
you can say that parseQueryString() is expected to return an object with CustomConfigPath property.
And from this:
var result = {};
you see that result is indeed an object ({} is an empty object literal). It is not an array. Later, in a loop, there is:
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
so we're assigning properties to the result object. One of this properties will be (as we can expect) a CustomConfigPath. This will be taken from the query string - we'll use regular expression to do this: re = /([^&=]+)=([^&]*)/g. So address of the webpage on which this code is executed looks like: http://example.com/something?SomeKey=value&CustomConfigPath=something.
General syntax for assigning properties to an object is:
result[key] = value;
// key -> decodeURIComponent(m[1])
// value -> decodeURIComponent(m[2])
parseQueryString().CustomConfigPath calls the parseQueryString function, which returns an object. Then it accesses the CustomConfigPath property of that object. A common idiom for the first 4 lines of the function is:
var customConfigPath = parseQueryString().CustomConfigPath || "/.customer-configuration";
var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m is a declaration of 4 different variables, not an array:
result is an empty object
queryString is the query string from the current URL, with the ? removed.
re is a regular expression
m is a variable that isn't initialized, it will be assigned later in the while loop.
Please check code below. Here all variable values are static.
var o = { level_a:{}, level_b:{}, . . . .};
var levelVar = "b";
var selected_tab = 'level'+'_'+levelVar; \\level_b
var result = o.selected_tab;
Here you can see var o is object and var levelVar and selected_tab are string. Now I expect I should get value of o.level_b inside result, but its not working becuse we can not concat string to object.
Please help.
Use this notation :
result = o[selected_tab];
More generally, when you have var obj={a:'b'}, you can access the property a using both obj.a and obj['a'].
Here's a MDN reference about the use of objects and properties.