0

I tried to Iterate json data in txt file using file(fs) module.its json data is string format but I want object format.how to achieve it.

amd.txt

{
 "first_name":"iball"
}
{
 "first_name":"ibell"
}  

product.js

fs.readFile("amd.txt","utf8", (err, data) => {
            if (err) throw err;
            let student = JSON.stringify(data);
            student = JSON.parse(student
            console.log(typeof student)
        });

Current output

string

excepted output

object
hari prasanth
  • 716
  • 1
  • 15
  • 35
  • You stringified a string, *why* did you expect that to parse to an object? – jonrsharpe Jul 29 '19 at 07:18
  • First, you shouldn't re-encode to JSON before parsing it (remove `let student = JSON.stringify(data);`, using `parse` only should be enough). Second, there's a formatting problem, you shouldn't have 2 objects in your JSON, but rather an array of objects – Kaddath Jul 29 '19 at 07:19

1 Answers1

3

I'd try this, change the file amd.txt like so:

[
    {
        "first_name":"iball"
    },
    {
        "first_name":"ibell"
    }
]

then change your code like so:

fs.readFile("amd.txt", "utf8", (err, data) => {
    if (err) throw err;
    students = JSON.parse(data);

    // Iterate list..
    console.log("Student list: ")
    students.forEach(student => {
        console.log(`First name: ${student.first_name}`);
    });
});

and I think you'll be much closer to the result you'd like!

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40