0

I'm trying to get a valid json from the data but JSON.stringify() returns only some values.

js file

var images = [];
[...files].forEach(function (file) {
            var reader = new FileReader();
            var srcData = file.webkitRelativePath;

            reader.onloadend = function () {
                images.push(reader.result);
            };
            reader.readAsDataURL(file);
            images.push(srcData);
        });

This results in the following output:

Console log output

Though after var temp = JSON.stringify({ images }); I only get the first 2 values even though all the values are strings.

> console.log(temp)
   // prints
   {"images":["images/1.jpg","images/1.png"]}

Any reason why JSON.stringify() acts like that?

Throvn
  • 795
  • 7
  • 19
  • Are the rest of the values not [valid for JSON representation](https://www.json.org/json-en.html)? – VLAZ Jun 19 '22 at 11:06
  • 1
    Also, are you sure those are the values you have *before* serialising? [The console is lazy](https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects) so it might not show you the values in the array as they were at that point in time. – VLAZ Jun 19 '22 at 11:08
  • @VLAZ aren't base64 string valid for JSON representation? – aditya miskin Jun 19 '22 at 11:09
  • @adityamiskin I think VLAZ is correct about the issue being about the console being lazy. You can see that in the non-expanded version of the array you only have 2 values, which is the array at the time of logging it, whereas the array when expanded is its contents at the time you expanded the array in the console. – Nick Parsons Jun 19 '22 at 11:13
  • 1
    If the missing entries are those pushed with `images.push(reader.result);` then your problem is that the `onloadend` is running after you call `.stringify()`. You're populating the array asynchronously within your for loop. – Nick Parsons Jun 19 '22 at 11:17
  • @NickParsons so how do I solve it? – aditya miskin Jun 19 '22 at 11:58
  • @adityamiskin there are a few ways, and it's made easier if you use Promises. See this answer [How to return the response from an asynchronous call](https://stackoverflow.com/a/43766002) – Nick Parsons Jun 19 '22 at 14:08

0 Answers0