Displaying Accurate JSON Data in JavaScript
As a web developer, especially when working with APIs and dynamic data, you often use console.log()
to inspect values and ensure everything is working as expected.
But have you ever faced a strange case where the value printed in the browser console does not match what’s actually in the database or API response? I did, and surprisingly, the solution was both simple and powerful: JSON.parse(JSON.stringify(...))
.
The Problem: Inconsistent Data in the Console
In one of my projects, I fetched data from a Laravel backend using AJAX:
$.ajax({
url: '/getDataToEstimate/1/wall/1/front',
type: 'GET',
success: function (response) {
console.log(response.data); // This log turned out to be misleading
}
});
According to the API, the value
for id_schedule = 12
should be 0
. But what showed up in the console was 6.4
. When I accessed the same URL directly in the browser, the value was correct!
Why This Happens: console.log()
Logs a Reference, Not a Snapshot?
When you do:
console.log(response.data);
The browser doesn’t immediately print the contents. Instead, it stores a reference to the object and renders it lazily in the console.
So if the object changes later, whether due to reactivity, JavaScript operations, or data mutation, the console may show the updated value, not the one at the time of logging.
This is what caused the discrepancy I saw.
The Solution: Freeze the Object with JSON.parse(JSON.stringify(...))
Here’s the simple trick that solved the issue:
console.log(JSON.parse(JSON.stringify(response.data)));
This does two things:
- Converts the object into a string (breaking references and stripping functions).
- Immediately parses it back into a plain JavaScript object.
The result is a frozen snapshot of your data—an accurate, reference-free version when you call it.