【问题标题】:change array to json将数组更改为 json
【发布时间】:2013-12-17 05:15:55
【问题描述】:

我一直在玩 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"
}

提前致谢。

【问题讨论】:

    标签: javascript json casperjs


    【解决方案1】:

    你可以这样使用:

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

    更新

    &gt; 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;
    });
    

    【讨论】:

    • 不知道为什么。买我的输出是这样的。 { \"Address\": \"address\", \"City\": \"city\", \"State\": \"state\", \"Zip\": \"zip\" }
    • 将线路更改为var json = arrayToObject(myArray); 为我做了这件事。谢谢。
    • 如何更改它以仅拆分第一次出现的冒号?我有一些像“计划开始:08:16 AM”这样的行,我的输出是“计划开始”:“08”我试过“var keyvalue = element.split(':',1);”但这没有用。
    猜你喜欢
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2020-05-19
    • 2020-04-14
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多