0

Is it possible to create an object from a string content?

For example, I have a string "{ name: John }" how can I simply parse it to create an object { name: 'John' } ?

UPDATE

Unfortunately JSON.parse won't work for me, there can be also some tricky strings (if you used mongodb you know), e.g. { name: John, email: { $exists: true } }

Maybe there is another solution like mongodb query parser?

Kosmetika
  • 20,774
  • 37
  • 108
  • 172

3 Answers3

2

this is one way to do it. //code for trim method

 if(typeof String.prototype.trim !== 'function') {
      String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, ''); 
      }
    }

    var s =  "{ name: John }";
    var arr = s.substring(1,s.length-1).trim().split(':');
    var obj = {};
    obj[arr[0]]=arr[1];

    alert(obj.name);
mrida
  • 1,157
  • 1
  • 10
  • 16
0

If you can get '{"name":"John"}' then you can just decode it as JSON.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Working jsFiddle Demo

Your string must be valid JSON format:

var s = '{ "name": "John", "family": "Resig" }';

Then you can parse it with JSON.parse:

var o = JSON.parse(s);

And you can use the object o:

alert(o.name); // John
alert(o.family); // Resig
  • unfortunately I can't be sure that it will be correct JSON, a string could be like this ``{ data: $exists }``, seems only spliting & slicing may help – Kosmetika Jun 01 '13 at 07:45
  • 1
    @Kosmetika How are you generating your JSON? All server side languages has ability to generate **valid** JSON string. –  Jun 01 '13 at 07:47
  • it's not a JSON, it's simple string that user puts into shell – Kosmetika Jun 01 '13 at 07:55
  • @Kosmetika I don't think it's a correct way to do this. Imagine user wants something like this: `{ "fullname": "Resig, John: jQuery Creator" }` (an object with one pair). How this must be input? `{ fullname: Resig, John: jQuery Creator }` (an object with two pairs)? –  Jun 01 '13 at 08:01
  • yeah, sounds not ok.. in ideal it can be typed like { fullname: "Resig, John: jQuery Creator" }.. – Kosmetika Jun 01 '13 at 08:13