[英]converting array into json format in nodejs
嗨,我有一个由数据组成的列表,我希望这些数据采用特定的 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/cbaa5e650152a0332b49400074985b6e-0.png
您可以执行以下操作
console.log(JSON.stringify(list, undefined, 2));
第一个参数对列表进行字符串化,老实说,第二个我不知道它有什么作用,但您必须包含它,第三个是您在格式中需要的缩进数。
您只是在list
数组中推送原始值。 您可能希望在listAllKeys
函数中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
函数中,否则它可以保存您从第一次开始调用该函数时获得的所有值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.