C json to new object
You want to convert a JSON string to a new object in JavaScript. You can use the JSON.parse()
method to achieve this.
Here's an example:
const jsonString = '{"name": "John", "age": 30}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject); // Output: { name: "John", age: 30 }
In this example, jsonString
is a JSON string, and JSON.parse()
converts it to a JavaScript object, which is stored in the jsonObject
variable.
Note that JSON.parse()
throws a SyntaxError
if the JSON string is malformed or cannot be parsed.
Alternatively, you can use the Object.create()
method to create a new object and then assign the JSON properties to it:
const jsonString = '{"name": "John", "age": 30}';
const jsonObject = Object.create(null);
jsonObject.name = jsonString.name;
jsonObject.age = jsonString.age;
console.log(jsonObject); // Output: { name: "John", age: 30 }
However, this approach is less efficient and less common than using JSON.parse()
.