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
2
  • You stringified a string, why did you expect that to parse to an object? Commented Jul 29, 2019 at 7: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 Commented Jul 29, 2019 at 7:19

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.