2

I have an object like:

    [
        {
          "text" : "Address of Bowlers game center in Chennai?",
          "entities" : [
            {
              "entity" : "action",
              "value" : "business"
            },
            {
              "entity" : "intent",
              "value" : "fetchItems"
            },
            {
              "entity" : "bizCategory",
              "value" : "bowling",
              "start" : 11,
              "end" : 30
            },
            {
              "entity" : "wit$location",
              "value" : "Chennai",
              "start" : 34,
              "end" : 40
            }
          ]
        },
        {
          .....more objects
        }
]

Now I have to do some manipulation on this object and save the manipulated object into an .json file using angular js.

var originalObject = $http.get("data/chennai.json");
var manipuatedObject;  // this is the manipulated object i get after applying some changes on originatalObject.

Now how can I save this manipuatedObject into an json file.

User 101
  • 1,351
  • 3
  • 12
  • 18

1 Answers1

9

Try this:

function saveText(text, filename){
  var a = document.createElement('a');
  a.setAttribute('href', 'data:text/plain;charset=utf-u,'+encodeURIComponent(text));
  a.setAttribute('download', filename);
  a.click()
}

So a possible use might be:

var obj = {a: "Hello", b: "World");
saveText( JSON.stringify(obj), "filename.json" );
  • this is working thanks.... now is it possible that can i get the formatted json in the downloaded file. – User 101 Nov 01 '17 at 13:06
  • a little late, but yes, you can. Just pass null as the replacer (2nd parameter) and the space you want to use for ident the json (3rd parameter). Example 1 - ident the json file with 4 spaces: JSON.stringify(obj, null, 4). Example 2 - you want to ident the json file with a tab: JSON.stringify(obj, null, "\t") – rmpt Jul 25 '21 at 13:33