嗨,我有一个包含数据的列表,我希望此数据采用特定的json格式,如下所示:
[
{
"slideName": "s0",
"imageUrl":
"https://s3.amazonaws.com/lifestyle345/testing/slides/cbaa5e650152a0332b494f0074985b6e-0.png",
"txtUrl":
"https://s3.amazonaws.com/lifestyle345/testing/speeches/virtualReality.txt"
}
]
以下为代码:
var list = [];
var AWS = require('aws-sdk');
//var oldPrefix = 'texts/';
var s3 = new AWS.S3({params: {Bucket: 'lifestyle345'}});
exports.handler = (event, context, callback) => {
function listAllKeys(s3bucket, start, end) {
s3.listObjects({
Bucket: s3bucket,
Marker: start,
MaxKeys: 1000,
}, function(err, data) {
if (data.Contents) {
//console.log("Length" +data.Contents.length)
for (var i = 0; i < data.Contents.length; i++) {
var key = "https://s3.amazonaws.com/lifestyle345/" +
data.Contents[i].Key; //See above code for the structure of data.Contents
//console.log("KEY =" +key);
if (key.substring(0, 19) != end) {
list.push(key);
} else {
break; // break the loop if end arrived
}
}
console.log(list);
var jsonString = JSON.stringify(list );
//console.log('Total - ', list.length);
console.log(jsonString);
}
});
}
listAllKeys('lifestyle345', 'testing/slides', 'testing/speeches');
}
生成的输出:
'https://s3.amazonaws.com/lifestyle345/testing/slides/cbaa5e650152a0332b49400074985b6e-0.png', 'https://s3.amazonaws.com/lifestyle345/testing/slides/cbaa5e650152a0332b494f0074985b6e-1.png'
答案 0 :(得分:0)
您可以执行以下
console.log(JSON.stringify(list, undefined, 2));
第一个参数将列表字符串化,第二个我实在不知道它是做什么的,但是您必须将其包括在内,第三个参数是格式中所需缩进的数量。
答案 1 :(得分:0)
您仅在list
数组中推送原始值。您可能想要在listAllKeys
函数中将准备好的对象推入此处,或者在完成列表后创建对象。从您的命名(slideName,imageUrl和textUrl)来看,好像您还有更多东西。
相关部分(用简洁的javascript编写):
for (let i = 0; i < data.Contents.length; i++) {
const key = `https://s3.amazonaws.com/lifestyle345/${ data.Contents[i].Key }`;
if (key.substring(0, 19) != end) {
const endObject = {
slideName: 'Whatever slide. Where do you get the info from?',
imageUrl: key,
textUrl: 'whatever, also no info',
}
list.push(endObject );
}
}
如您所见,我将对象本身推入列表,而不仅仅是带有url的字符串。
或者,您也可以按照自己的方式对列表进行门控,最后将其循环并获取列表:
const list = [];
for (...) {
...
list.push(url);
}
// after you get the list of URLs, you get the objects:
const objects = list.map(function (url) {
return {
slideName: 'Whatever slide. Where do you get the info from?',
imageUrl: url,
textUrl: 'whatever, also no info',
}
});
console.log(JSON.stringify(objects, null, 2));
注释1 :我不知道您从何处获得textUrl
,所以我现在跳过它。
注释2 :最好在var list = []
函数内移动listAllKeys
语句,否则它可以保存从您第一次调用该函数起得到的所有值。