2013-12-17 166 views
1

我一直在玩javascript和casperjs。我有以下幾行代碼。將數組更改爲json

casper.thenOpen('somesite', function() { 

    console.log('clicked ok, new location is ' + this.getCurrentUrl()); 

    // Get info on all elements matching this CSS selector 
    var town_selector = 'div tr'; 
    var town_names_info = this.getElementsInfo(town_selector); // an array of object literals 

    // Pull out the town name text and push into the town_names array 
    var town_names = []; 
    for (var i = 0; i < town_names_info.length; i++) { 
    town_names.push(town_names_info[i].text.trim());} 

    // Dump the town_names array to screen 
    utils.dump(town_names);  

    casper.capture('capture5.png'); 
}); 

我的輸出是這樣的。

[ 
    "Address:\n  \n address", 
    "City:\n  \ncity", 
    "State:\n  \nstate", 
    "Zip:\n  \nzip", 
] 

我該如何讓它成爲json?喜歡這個。

{ 
    "Address":"address", 
    "City":"city", 
    "State":"state", 
    "Zip":"zip" 
} 

在此先感謝。

回答

4

您可以使用這樣的事情:

function arrayToObject(arr) { 
    var out = {}; 
    arr.forEach(function (element) { 
    var keyvalue = element.replace(/[\n\s]+/, '').split(':'); 
    var key = keyvalue[0]; 
    var value = keyvalue[1]; 
    out[key] = value; 
    }); 
    return out; 
} 

那麼你可以做:

var json = JSON.stringify(arrayToObject(myArray)); 

更新

> How can I change this to split only the first occurrence of colon?

使用此:

arr.forEach(function (element) { 
    var keyvalue = element.replace(/[\n\s]+/, ''); 
    var key = keyvalue.substring(0, element.indexOf(':')); 
    var value = keyvalue.substring(key.length + 1); 
    out[key] = value; 
}); 
+0

不知道爲什麼。買我的輸出是這個。 「城市\」:\「城市\」, \「州\」:\「州\」, \「郵政編碼」:\「 「 }' – fpena06

+0

將行更改爲'var json = arrayToObject(myArray);'爲我做了。謝謝。 – fpena06

+0

我該如何改變這種情況才能拆分第一個冒號?我有一些像「Planned Start:08:16 AM」這樣的行,我的輸出是「Planned Start」:「08」我試過了「var keyvalue = element.split(':',1);」但那不起作用。 – fpena06