I start from a JSON string, try to convert it into a JSON object and then I try to print one specific field (for example firstName), but I obtain undefined. What am I doing wrong? Thank you!
var string = '{"firstName":"John", "lastName":"Doe"}'
var obj = JSON.stringify(string)
var json_object = JSON.parse(obj)
console.log(json_object.firstName)
console.log(json_object['firstName'])
The string is string.
So you don't need to stringify that.
var string = '{"firstName":"John", "lastName":"Doe"}'
var json_object = JSON.parse(string)
console.log(json_object.firstName)
var string = '{"firstName":"John", "lastName":"Doe"}';
var obj = JSON.parse(string);
console.log(obj.firstName)
The object is a string, you only need to parse the JSON and print what you want. If you had created an JavaScript object, there you can use Stringify for stringifying, but it wouldn't be necessary. JSON Parse parses a String in JSON.
When you pass a string to JSON.stringify, that is equivalent to pass a string object to JSON.stringify.
After you execute the code below, you actually got the result '"{\\"firstName\\":\\"John\\", \\"lastName\\":\\"Doe\\"}"' of the variable obj.
var string = '{"firstName":"John", "lastName":"Doe"}'
var obj = JSON.stringify(string)
At the end, use JSON.parse to parse '"{\\"firstName\\":\\"John\\", \\"lastName\\":\\"Doe\\"}"' string, we will get the string object of '{"firstName":"John", "lastName":"Doe"}'.
For detail, you can check Autoboxing: primitive wrapper objects in JavaScript.
So, you can just remove JSON.stringify(string), and pass '{"firstName":"John", "lastName":"Doe"}' to JSON.parse directly.