Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

jquery - Need to convert json key-value pairs to standard array

I'm interperting a json string into a variable using jquery's parseJSON() function. The problem is, it's turning my data into an object instead of a 2d array. Eg,

myData = $.parse(JSON(data));
myData.name// = "Bob"

The problem is, "name" is not supposed to be a key (assuming that is the correct term). Instead, it should be:

myData[0] // = "name"
myData[1] // = "Bob"

How would I convert this? Or is there a different method than using a for loop to walk through the index of an array (but still be able to access both key and value as a string, as you would in a 2d array).

EDIT: This is some json that is in use (Note it's MUCH longer). This is what is given for "data"

{"feat_3":"4356","feat_4":"45","feat_5":"564","feat_6":"7566"}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Once you've deserialized the data (e.g., you have myData, which is an object), you can loop through its keys using for..in, and then build up an array that combines keys and values:

var myData, dataArray, key;
myData = $.parse(JSON(data));
dataArray = [];
for (key in myData) {
    dataArray.push(key);         // Push the key on the array
    dataArray.push(myData[key]); // Push the key's value on the array
}

Since myData is the result of deserializing the JSON in data, we know that myData is a generic object (e.g., just a {} as opposed to a new Foo or something like that), so we don't even need hasOwnProperty. If we didn't know that, and we only wanted to enumerate myData's own keys and values, we would add a hasOwnProperty check:

var myData, dataArray, key;
myData = $.parse(JSON(data));
dataArray = [];
for (key in myData) {
    if (myData.hasOwnProperty(key)) {
        dataArray.push(key);         // Push the key on the array
        dataArray.push(myData[key]); // Push the key's value on the array
    }
}

There's no reason to do that in your case, unless someone has been mucking about with Object.prototype (in which case, take them behind the woodshed, give them a severe hiding, and then have them write "I will not muck about with Object.prototype several hundred times on the chalkboard), but whenever you use for..in, it's always good to stop and think whether A) The object is guaranteed to be vanilla, and B) If not, do you want only its own properties, or do you also want ones it inherits?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...