Reputation: 335
Let's say we have a file (*.csv, *.txt ...) like :
Name, Surname, Age, Occupation
Gino, DiNanni, 19, student
Anna, Kournikova, 27, programmer
(I added those spaces just to make it readable here)
I'm trying to create a JSON (BTW it's valid) like:
[
{
"gino_dinanni": [
{
"age": "19",
"occupation": "student",
}
]
},
{
"anna_kournikova": [
{
"age": "27",
"occupation": "programmer",
}
]
}
]
accessible like e.g.
anna_kournikova.age // 27
So far I have this http://jsbin.com/apapey/2/edit but this is giving me (awfully):
[["Age:19","Occupation:student"],["Age:27","Occupation:programmer"]]
I know how to use .toLowerCase()
to create anna_kournikova
and stuff, but I'm really lost in creating the right JSON "object". I would paste some better examples I tried before, but I erased them all in a fit of rage, now going back from scratch and I need your advice. Might be I'm missing a simple detail? Thanks so much!
Upvotes: 1
Views: 528
Reputation: 7550
Definitely you can try some meta programming, using JavaScript :)
var json =[{"gino_dinanni": [{"age": "19","occupation": "student",}]},{"anna_kournikova": [{"age": "27","occupation": "programmer",}]}];
document.write(getAge('gino_dinanni'));
function getAge(name){
return eval("json[0]."+name+"[0].age");
};
Upvotes: 0
Reputation: 1
You could see this page http://www.cparker15.com/code/utilities/csv-to-json/
The project in Github is https://github.com/cparker15/csv-to-json/issues
Upvotes: 0
Reputation: 191819
http://jsbin.com/ihivuj/2/edit
I've changed it to what I believe is your intended format.
The ..stringify
is probably not necessary for printing if you want to work with a real JSON object. You were trying to work with some mixture of strings/arrays.
You can use the bracket syntax to add elements to objects, but do not treat them as arrays:
arr[oneData[0] + oneData[1]][headers[2]] = oneData[2];
You can't combine brace syntax with concatenation/variables for key names either.
Upvotes: 1
Reputation: 1226
If you are able to change the markup of your JSON, this would yield better results,
{
"gino_dinanni": {
"age": "19",
"occupation": "student"
},
"anna_kournikova": {
"age": "27",
"occupation": "programmer"
}
};
That way you can use data.anna_kournikova.age
. As other users have suggested, your CSV should be parsed on the server side and you can just use jQuery.getJSON( ... )
to retrieve it
Upvotes: 3