React-native-fs: Extra bracket when saving a JSON file

Created on 21 Mar 2020  路  3Comments  路  Source: itinance/react-native-fs

In my app, I save a JSON file, and somewhere I load it back.
But when I try to load it back, the parsing process fails:
The saved JSON file as an extra bracket at the end.

馃帹 馃摳

Here is a screenshot

extra-bracket

So I saved the file in RNFS.DownloadDirectoryPath so I can check it myself from a File Explorer, and yeah, the file on the disk really has an extra bracket. The JSON is invalid.

馃 馃槴

What's could be the problem? Can someone help?

Versions:

"react": "16.9.0",
"react-native": "0.61.5",
"react-native-fs": "^2.16.6",

Most helpful comment

馃槷 馃槂

Ok, I figured it out.
Workaround: delete the file first.

Here is my actual scenario:

  • Create an object
  • Stringify the object
  • Persist the object (at this step, persisted JSON is valid)
  • Update the object: changing a field from false to true
  • Stringify the object
  • Persist the object (at this step, persisted JSON has an extra bracket)

The reason is, writeFile() writes over the file, without clearing the content first.

So, if I run

await RNSF.writeFile('lorem.txt', 'hello world !!');
await RNSF.writeFile('lorem.txt', 'hello you');

The file will contain

hello yould !!
         ^^^^^
         From the previous content

Tested and Android.

All 3 comments

馃槷 馃槂

Ok, I figured it out.
Workaround: delete the file first.

Here is my actual scenario:

  • Create an object
  • Stringify the object
  • Persist the object (at this step, persisted JSON is valid)
  • Update the object: changing a field from false to true
  • Stringify the object
  • Persist the object (at this step, persisted JSON has an extra bracket)

The reason is, writeFile() writes over the file, without clearing the content first.

So, if I run

await RNSF.writeFile('lorem.txt', 'hello world !!');
await RNSF.writeFile('lorem.txt', 'hello you');

The file will contain

hello yould !!
         ^^^^^
         From the previous content

Tested and Android.

Thank you!

Still an issue, thanks for the workaround 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

opoze picture opoze  路  3Comments

ToJen picture ToJen  路  4Comments

1556173267 picture 1556173267  路  3Comments

wangfpp picture wangfpp  路  3Comments

7korobi picture 7korobi  路  4Comments