117

I'm trying to initialize an object in typescript which requires a JSON string for the "options" parameter. To be precise it is the object here. The options parameter is required to be a JSON string and not an object for initializing the dijit.

Is there a way to create a JSON string from a typescript object without it being a manual process?

Please DO NOT link any questions which don't specifically say "TypeScript" as this question specifically relates to TypeScript. While a derivative of JavaScript the way that you write code is different and therefore this is the only post asking this question currently relating to TypeScript.

user1567453
  • 1,837
  • 2
  • 19
  • 22
  • 3
    Are you sure you need a JSON string? It looks like it just takes an object. But you can convert any object (assuming it doesn't have cycles) to JSON by using [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) – Mike Cluck Feb 12 '16 at 00:04
  • Thanks Mike, I will give it a go as an object but keep the question regardless since it might be useful to someone else (or still me) in the future :) – user1567453 Feb 12 '16 at 00:12

5 Answers5

247

Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.

Curtis
  • 101,612
  • 66
  • 270
  • 352
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
  • Probably going to choose this one as the answer since it explains why I can use JSON.stringify in Typescript. Can't accept before 8 minutes XD will see what pops up. – user1567453 Feb 12 '16 at 00:09
  • 3
    With proper object definitions following the following guide, this wont work because all the keys will use the private variable names (if an underscore is used with your private members) https://www.typescriptlang.org/docs/handbook/classes.html#public-private-and-protected-modifiers – jarodsmk Jun 07 '17 at 08:10
  • 1
    @N15M0_jk Yes, I have noticed that too. I'm using JSON.stringify(obj).replace(/"_/g, '"') to overcome that issue. – HammerNL Jul 06 '17 at 08:16
  • I used JSON.stringify(object) and it performed without any problems at all on https://www.fireboxtools.com/json-tools/json-to-string. – jitendra rajput Aug 06 '23 at 14:38
14

TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:

  • JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
  • JSON.stringify() method converts a JavaScript object or value to a JSON string.

Example:

const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';


const JSobj = JSON.parse(jsonString);

console.log(JSobj);
console.log(typeof JSobj);

const JSON_string = JSON.stringify(JSobj);

console.log(JSON_string);
console.log(typeof JSON_string);
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
8

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);
Giovanni P.
  • 1,017
  • 15
  • 23
3

Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.

const temp = [];
const t = {
  name: "name",
  etc: [{
    a: 0
  }],
};
for (let i = 0; i < 3; i++) {
  const bla = Object.assign({}, t);
  bla.name = bla.name + i;
  bla.etc[0].a = i;
  temp.push(bla);
}

console.log(JSON.stringify(temp));
enzo
  • 9,861
  • 3
  • 15
  • 38
Oliver Groß
  • 121
  • 1
  • 5
  • 2
    That's probably because Object.assign does not deep-clone an object. Therefore, all your instances share the very same `etc` array, which is then modified on each iteration, so you should end up with 2 in all of those arrays. Nothing to do with JSON.stringify here. – Jan Papenbrock Apr 10 '20 at 15:57
0

If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:

const fsExtra = require('fs-extra');

fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
  console.log('success!')
})
.catch(err => {
  console.error(err)
})
Paul Razvan Berg
  • 16,949
  • 9
  • 76
  • 114