146

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 parameter is required to be a JSON string and not an object.

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

2
  • 4
    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 Commented Feb 12, 2016 at 0: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 :) Commented Feb 12, 2016 at 0:12

5 Answers 5

288

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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) typescriptlang.org/docs/handbook/…
@N15M0_jk Yes, I have noticed that too. I'm using JSON.stringify(obj).replace(/"_/g, '"') to overcome that issue.
I used JSON.stringify(object) and it performed without any problems at all on fireboxtools.com/json-tools/json-to-string.
24

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);

Comments

9

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

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

Comments

2

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));

1 Comment

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.
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)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.