jsaunders
jsaunders

Reputation: 11

str.split to json with names

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

Upvotes: 1

Views: 164

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

["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.

Upvotes: 1

adam-beck
adam-beck

Reputation: 6009

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 [].

Upvotes: 1

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

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

Upvotes: 0

Related Questions