I have a PHP file where I have the name of the files of one folder and my objective now is to output this array as JSON.
My array looks like this:
Array (
[0] => teste3.pdf
[1] => teste2.pdf
[2] => teste.pdf
[3] => ..
[4] => .
)
And I'd like my JSON structured like this:
{
"Documents": [
{
"NameDoc": "teste3.pdf"
},
{
"NameDoc": "teste2.pdf"
},
{
"NameDoc": "teste.pdf"
},
]
}
I tried using json_encode
but this alone doesn't give me what I want.
Assuming your array of files is called MyArr
.
const obj = {
Documents: MyArr.map(file => ({ NameDoc: file }))
}
Now do whatever you want to do with obj
.
let myArray = [
'teste3.pdf',
'teste2.pdf',
'teste.pdf'
];
let obj = {
Documents: myArray.map( item => ({ NameDoc: item }))
};
let jsonString = JSON.stringify(obj);
It makes sense to tackle the problem at the source if you're using PHP to create the data:
$arr = ['teste3.pdf', 'teste2.pdf', 'teste.pdf'];
$map = array_map(function($name){
return ['NameDoc' => $name];
}, $arr);
echo json_encode([
'Documents' => $map
]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.