str.split to json with names - javascript

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);

Related

How to convert a string to a template string

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

I want to make Javascript object dynamic

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

Dynamically add object in javascript array

I have json:
var obj = '{"Form":[],"Provider":[]}';
I push the data with variable value to make dynamic objects:
var pName = 'Tester';
var data = {
pName :["testing"]
};
console.log(obj['Provider'].push(data));
But that adds pName as variable name but not variable value that is Tester, i tried with +pName+ that also not works.
Returns:
{"Form":[],"Provider":[{"pName":["Testing"]}]}
Any help would be appreciated.
You must use [] syntax near the property name.It will evaluate the expression in the [] and returns the value.
See the example.Here the data's property is with the name 'Tester'.
var obj = {"Form":[],"Provider":[]};
var pName = 'Tester';
var data = {
[pName] :["testing"]
};
console.log(data.pName); // undefined
console.log(data.Tester); // OK
obj['Provider'].push(data);
console.log(obj);

accessing JSON value if key is array element

suppose i receive JSON object from the server as this
{ "asdf[zxcv]": "qwer" }
how do i access asdf, zxcv, and qwer in javascript, so i can use the object this way ?
theobj.asdf[zxcv] = 'qwer'
Bracket notation is not in the JSON RFC. You can only read it as string.
var simpleObj = {
"simpleKey": "simpleValue"
}
console.log(simpleObj)
var advObj = {
"advKey[1]": "advValue"
}
console.log(JSON.parse(advObj)); // SyntaxError
console.log(advObj.advKey[1]) // TypeError
console.log(advObj["advKey[1]"]) // can only read as string
You would need to refactor the source JSON into something more meaningful so you can access the values in regular JavaScript way.
Run the following snippet to check how you can solve the issue:
var x = '{ "asdf[zxcv]": "qwer" }';
var y = JSON.parse(x);
var result = Object.keys(y).reduce(function(result, key) {
var parentKey = key.substring(0, key.indexOf("["));
var innerKey = /[a-z]+\[([a-z]+)\]/i.exec(key)[1];
if (!result.hasOwnProperty(key))
result[parentKey] = {};
result[parentKey][innerKey] = y[key];
return result;
}, {});
document.getElementById("structure").textContent = JSON.stringify(result);
var zxcv = result["asdf"]["zxcv"];
document.getElementById("someValue").textContent = zxcv;
<h2>Refactored data structure as nested objects:</h2>
<div id="structure"></div>
<h2>Accessing some value: result["asdf"]["zxcv"] or result.asdf.zxcv</h2>
<div id="someValue"></div>
It's all about creating nested objects to represent the associative keys in the source JSON properties representing a conceptual associative array...
This is one of the way to access all elements without reconstructing object.
jQuery.each(JSON.parse('{ "asdf[zxcv]": "qwer" }'), function(index, value) {
var i = index;// i = "asdf[zxcv]"
var v = value;// v = "qwer"
var iOfInnerValue = (/\[(.*?)\]/g).exec(i)[1];// innerValue = "zxcv"
var iOfOuterValue = index.replace("["+(/\[(.*?)\]/g).exec(i)[1]+"]",""); // outerValue = "asdf"
});
You'll need to assign the data to a variable and then you can use Object keys to get the key which is the part before the :. Here's an example.
var j = { "asdf[zxcv]": "qwer" };
console.log(Object.keys(j)); //["asdf[zxcv]"]
console.log(j); //{asdf[zxcv]: "qwer"}

How to access first element of JSON object array?

I exptect that mandrill_events only contains one object. How do I access its event-property?
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' }
console.log(Object.keys(req)[0]);
Make any Object array (req), then simply do Object.keys(req)[0] to pick the first key in the Object array.
To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.
So either correct your source to:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
and then req.mandrill_events[0], or if you're stuck with it being a string, parse the JSON the string contains:
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];
the event property seems to be string first you have to parse it to json :
var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var event = JSON.parse(req.mandrill_events);
var ts = event[0].ts
I'll explain this with a general example:
var obj = { name: "John", age: 30, city: "New York" };
var result = obj[Object.keys(obj)[0]];
The result variable will have the value "John"
'[{"event":"inbound","ts":1426249238}]' is a string, you cannot access any properties there. You will have to parse it to an object, with JSON.parse() and then handle it like a normal object
After you parse it with Javascript, try this:
mandrill_events[0].event
Assuming thant the content of mandrill_events is an object (not a string), you can also use shift() function:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
var event-property = req.mandrill_events.shift().event;

Categories

Resources