将数组更改为json

时间:2013-12-17 05:15:55

标签: javascript json casperjs

我一直在玩javascript和casperjs。我有以下几行代码。

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

提前致谢。

1 个答案:

答案 0 :(得分: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;
});