javascript 将字符串json中的number修改为string in javascript

To convert a number to a string in a JSON string using JavaScript, you can use the JSON.stringify() method with a replacer function to modify the value of each numeric property before it gets serialized.

Here's an example:

index.tsx
const obj = {
  name: 'John',
  age: 30,
  salary: 2500
};

const replacer = (key, value) => typeof value === 'number' ? value.toString() : value;

const jsonString = JSON.stringify(obj, replacer);

console.log(jsonString);
// output: {"name":"John","age":"30","salary":"2500"}
278 chars
13 lines

In this example, we define an object obj with some properties including age and salary which are of type number. We also define a replacer function that checks if the value is a number, and if so, returns the string representation of the number. We then call JSON.stringify() method with the replacer function as the second argument to convert our object to a JSON string with the number properties as string.

The jsonString variable will now contain the JSON string with the numeric properties in string format.

gistlibby LogSnag