I have this data in a .jl file which I would like to convert into a JSON array:
I am supposed to receive data from a server, which sends it in a .jl format. However, I have written my program in Node.js and the only way I know to use the data is in JSON format from a .json file. I have shared the .jl file code I have and the .json format I would like to convert it into below. (At the moment I have manually retyped the data in the .jl file to .json format). Does anyone know how to convert the data from the .jl file into data in a JSON array as shown on my code below?
// .jl data:
{
"FName": "Peter",
"ONames": ["Mc", "West"],
"Hobbies": ["Football", "Basketball"],
"Age": 18
},
{
"FName": "Edward",
"ONames": ["Mc", "Fly"],
"Hobbies": ["Tennis", "PlayStation"],
"Age": 19
},
{
"FName": "Winnie",
"ONames": ["Honey", "Pooh"],
"Hobbies": ["Boxing", "Basketball"],
"Age": 28
}
What I'm hoping to achieve is the following:
// Expected JSON array format:
[
{
"FName": "Peter",
"ONames": ["Mc", "West"],
"Hobbies": ["Football", "Basketball"],
"Age": "18"
},
{
"FName": "Edward",
"ONames": ["Mc", "Fly"],
"Hobbies": ["Tennis", "PlayStation"],
"Age": "19"
},
{
"FName": "Winnie",
"ONames": ["Honey", "Pooh"],
"Hobbies": ["Boxing", "Basketball"],
"Age": "28"
}
]
I think what you're asking is how to read content from .jl
file?
Since .jl
is a text document in utf8 encoding & you only need to wrap the content inside bracket, you can use fs.readFile
with encoding set to 'utf8', wrap it in brackets then write that string into a .json file. Here's an example with fs.readFileSync()
:
const fs = require('fs');
const content = fs.readFileSync('./test.jl', 'utf8');
fs.writeFile('./test.json', `[${content}]`, (err) => {
if (err) throw err;
console.log('saved as json')
})
I don't know .jl
at all, so I'm not sure what you'd need to watch out for syntax-wise. For your use case though this should work.
Edit: If you just want to consume the file immediately, instead of writing it out to a .json
, you could do:
const fs = require('fs');
const content = fs.readFileSync('./test.jl', 'utf8');
const data = JSON.parse(`[${content}]`);
If your .jl
is really really massive, look into using stream.
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.