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?
-
2You need json format String in order to convert it to JSon Object. and which platform ?Jigar Joshi– Jigar Joshi2011-11-10 07:41:34 +00:00Commented Nov 10, 2011 at 7:41
3 Answers
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.
4 Comments
[] or a {}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"