简体   繁体   中英

How to convert data to JSON

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 eg

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!

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM