How to create a json file - Ionic 3


#1

Hi, how Can I create a json file ? somebody has any example?


#2

if you have a JSON object, all you need to do is write it to wherever you want. For example, you can use Ionic Storage set method to write the object into a database (sqlite, indexed, websql etc). The get/set operations take care of serializing and de-serealizing. If you are looking to create a text file and not a record inside some form of DB, you can use Ionic Native’s File plugin to create a “.json” file wherever you want - you’ll likely do a JSON.stringify to your object to store it and then JSON.parse() to decode it back to your object on read.


#3

Sorry, I didn’t clarify my doubt, I need to create json file and download it to a fisically folder in my device.


#5

My answer remains the same. Its possible I’m still misunderstanding your question. You can use ionic native File as I wrote above. Note that any application can only write to specific folders inside its sandbox.

so your code would be something like:

import { File } from '@ionic-native/file';
constructor (public file:File,...) { ...}

then to write your structure to a local file on the device:

writeJSON(filename, object) {
// object is the data you need to write as json
// filename is the filename
// no error checking done - just an example
return this.file.writeFile(this.file.dataDirectory, filename, JSON.stringify(object), {replace:true})
}

Call it with

writeJSON('mydata.json', {a:'foo', b:'bar'})

#6

I try it, but doesn’t work, I’m using Android platform, Do You know what specific folder I have to use?


#7

You’ll have to read this and fully understand the paths/ways to access. If things don’t work, you’ll need to post code along with explicit error messages. You can also google search - there are multiple examples on how to use the plugin


#8

Hi @efbarbosa,
Did you get success to create json file ?


#9

It works for me with this.file.externalRootDirectory