[英]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.