2
Id: {
    editable: false,
    nullable: true
},
CustomerID: {
    editable: true,
    type: Integer
},
CompanyName: {
    editable: true,
    type: String
},
ContactName: {
    editable: true,
    type: String
}

Hi, is there a way in javascript or jquery where I could convert this String into an Object?

Thanks.

3
  • 2
    How do you get that string? Commented Mar 25, 2015 at 2:17
  • JSON doesn't support function values (like String or Integer. also not supported in all browsers (versions) Commented Mar 25, 2015 at 3:07
  • That string should be dynamic, I read fields from a database table Commented Mar 25, 2015 at 3:08

4 Answers 4

3

If that is strictly the format of the string then it's invalid JSON. However, you can get around this issue with judicious use of eval():

eval('myobj = {' + stringifiedObject + '};');

As clarification, the reason you cannot use JSON.parse() here is that the JSON specification requires that all keys are quoted.

JSON.parse('{ ID: 1 }');   // Generates an exception: Invalid character
JSON.parse('{ "ID": 1 }'); // Returns object: { ID: 1 }
Sign up to request clarification or add additional context in comments.

Comments

0

Based on the @Phylogenesis answer but without the eval.

Wrap the -almost- object and then run a JSON.parse.

var myObj;

stringifiedObject = '{' + stringifiedObject + '}';
myObj = JSON.parse(stringifiedObject);

Note: If you don't know the origin (or format) of the string you'd like to pase, then you can wrap the JSON.parse line between a try..catch() statement.

2 Comments

Unfortunately, this won't work. The JSON specification requires that key names are quoted: { "Id": { "editable": false, "nullable": true }, ...}. Running JSON.parse() on your example will generate an exception.
@Phylogenesis you're right, your answer is definitely better then.
0

I would use a combination of both existing answers

var new_string = JSON.parse((string.trim().charAt(0)!=='{')?('{'+string+'}'):string);

Assuming string is your input, and new_string is your output

Comments

0

This may work for you,

var mystring="[Id: {
    editable: false,
    nullable: true
},
CustomerID: {
    editable: true,
    type: Integer
},
CompanyName: {
    editable: true,
    type: String
},
ContactName: {
    editable: true,
    type: String
}]";

var obj1 = JSON.parse(mystring);

OR 

var obj2= eval('(' + mystring+ ')');

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.