0

I have some problems with the length in a byte of data get from a file. In my case, I use the readFileSync method to get data from a text file. But when I do something like the below code. It gives me 2 difference results.

let data = fs.readFileSync('size.txt');
console.log(data.length);
console.log(JSON.stringify(JSON.parse(data)).length);

Result in: 579859 (console log 1) and 409065 (console log 2)

So, I don't understand why the size is decreased after I parsed it to JSON and then I use the stringify method.

Thank you for any helping!

2
  • Show us what the original data is and then and ONLY then can we answer. Have you compared the two yourself to see what the differences are? It could very well be differences in spaces or linebreaks. Output the second to a file and compare it with a diff tool. This seems like a problem you should just be examining the data yourself rather than asking us. JSON is not a format that is entirely canonical with only one exact way to express the same underlying data. Questions here should show that you put some effort into diagnosing the problem yourself before coming here. Commented Nov 20, 2019 at 16:45
  • @jfriend00. The data file is very big. I can not show them here. This is a nice answer " It could very well be differences in spaces or linebreaks". Thank you for your answer. You saved my life. Commented Nov 21, 2019 at 3:09

1 Answer 1

1

JSON.stringify will not restore the spaces like in the below example :

const obj = `{
  "keyA": "obiwan kenobi",
  "testB": "foo"
}`;

console.log(obj);

const obj2 = JSON.stringify(JSON.parse(obj));

console.log(obj.length, obj2.length);

console.log(obj2);

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

1 Comment

So, this is the best answer and a good example to explain to me. Thank you for your helping. @Grégory NEUT

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.