I know the method to convert a JS object into a JSON string by using JSON.stringify(object)
method. How can I encode a string object into JSON?
Same way:
var jsonEncodedString = JSON.stringify(string);
or are you asking for the revsere
var jsonString = JSON.stringify({hello:"world"}),
jsObject = JSON.parse(jsonString);
You can't convert a string into JSON. The outermost data type in JSON must be an object or an array.
See the specification :
JSON Grammar
A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.
A JSON text is a serialized object or array.
You could wrap the string in an object or array and then serialise that:
JSON.stringify([myString]);
JSON.stringify({foo: myString});
Whatever processed it would have to know that after parsing the JSON it would have to extract the string from it though.
I think you're looking for the JSON.parse function .
var jsonString = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsonString);
var fullname = contact.surname + ", " + contact.firstname;
// The value of fullname is "Aaberg, Jesper"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.