1

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?

1
  • 2
    You need json format String in order to convert it to JSon Object. and which platform ? Commented Nov 10, 2011 at 7:41

3 Answers 3

4

Same way:

var jsonEncodedString = JSON.stringify(string);

or are you asking for the revsere

var jsonString = JSON.stringify({hello:"world"}),
jsObject = JSON.parse(jsonString);
Sign up to request clarification or add additional context in comments.

2 Comments

@Tom... it is giving script error as exception thrown not caught... in json2.js at line number 447
Then what you have probably isn't correctly formatted json, catch and report the exception.
3

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

@Quentin.... suppose i have string like var str ="MyName" Am i able to use JSON.stringify(str)
No! A string isn't a [] or a {}
SO then need to parse like... JSON.parse({str}) or JSON.parse([str]) ?
No. You pass a string (containing JSON) to JSON.parse and get a JS object back. If the JSON text starts with an object, you get an object. If it starts with an array, you get an array. You need to put an object or array into stringify not parse.
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.