我有以下javascript代码,我使用casperjs迭代一些链接并以json格式返回一些数据。
这是我的代码段
casper.each(links, function (self, link) {
this.thenOpen(link, function () {
//get work order info
var town_selector = 'div tr';
var town_names_info = this.getElementsInfo(town_selector);
var town_names = [];
for (var i = 0; i < town_names_info.length; i++) {
town_names.push(town_names_info[i].text.trim().replace(/\n\s+\n/, ''));
}
var jsonTest = arrayToObject(town_names);
json.push(JSON.stringify(jsonTest));
casper.capture('./images/workOrder' + workOrder + '.png');
workOrder++
utils.dump(jsonTest);
array.push(jsonTest);
casper.thenClick(x('/html/body/table[2]/tbody/tr/td[2]/a[2]'), function () {
//more some stuff here
someLinks = this.evaluate(getLinks);
for (var i = 0; i < someLinks.length; i++) {
someLinks[i] = "https://somelink" + someLinks[i];
}
casper.each(someLinks, function (self, link) {
self.thenOpen(link, function () {
var selector = 'div tr';
var names_info = this.getElementsInfo(town_selector);
var names = [];
for (var i = 0; i < names_info.length; i++) {
names.push(names_info[i].text.trim().replace(/\n\s+\n/, ''));
}
var jsonTest = arrayToObject(names);
json.push(JSON.stringify(jsonTest));
utils.dump(jsonTest);
array.push(jsonTest);
fs.write('results.json', JSON.stringify(array), 'w');
casper.capture('./images/lineItem' + lineItem + '.png');
lineItem++
});
});
});
});
});
以下是两个活动的输出,每个活动有两个订单项。
[{"Activity #":"some activity",
"Customer":"some customer",
"Account #":"some account"},
{
"Line #":"1",
"Action Required":"",
"Status":"some status",
"Product Line":"some product line",
"Product":"some product"},
{
"Line #":"2",
"Action Required":"",
"Status":"some status",
"Product Line":"some product line",
"Product":"some product"},
{
"Activity #":"some other activity",
"Customer":"some other customer",
"Account #":"some other account"},
{
"Line #":"1",
"Action Required":"",
"Status":"some status",
"Product Line":"some product line",
"Product":"some product"},
{
"Line #":"2",
"Action Required":"",
"Status":"some status",
"Product Line":"some product line",
"Product":"some product"}]
有人可以帮助我让我的输出看起来像这样吗?
[{
"Activity #": "some activity",
"Customer": "some customer",
"Account #": "some account",
"lineItems": [
{
"Line #": "1",
"Action Required": "",
"Status": "some status",
"Product Line": "some product line",
"Product": "some product"
},
{
"Line #": "2",
"Action Required": "",
"Status": "some status",
"Product Line": "some product line",
"Product": "some product"
}
]
},
{
"Activity #": "some activity",
"Customer": "some customer",
"Account #": "some account",
"lineItems": [
{
"Line #": "1",
"Action Required": "",
"Status": "some status",
"Product Line": "some product line",
"Product": "some product"
},
{
"Line #": "2",
"Action Required": "",
"Status": "some status",
"Product Line": "some product line",
"Product": "some product"
}
]
}
]
提前谢谢。
答案 0 :(得分:0)
使用JSON.stringify
的适当参数应该这样做:
fs.write('results.json', JSON.stringify(array, null, 4), 'w');