Skip to main content
1 of 4

A valid JSON string is easily turned into objects, but the value you've got for "$t" is not valid JSON and no compliant parser will touch it (as you discovered). Your best option, if possible (it often isn't), would be to fix the code that's emitting that JSON-parody string. But it looks to me like that's not a possibility here.

If you can trust your source to keep cranking out this stuff in the same format more or less indefinitely, you can fall back on an ugly regex solution:

function parseCompany(str) { var re = /name:\s*([^,]+),\s*price:\s*(-?[\d\.]+),\s*change:\s*(-?[\d\.]+)/; var result = null; str.replace(re, function ($0, name, price, change) { result = { name: name, price: parseFloat(price), change: parseFloat(change) }; }); return result } var co = parseCompany("name: ANGLO AMERICAN, price: 1547, change: 8.5"); alert(co.name); co = parseCompany("name: BRIT AMER TOBACCO, price: 3407, change: -8.5"); alert(co.name); 

You should never parse anything with regexes if a standard parser exists for the format (JSON, XML, etc.), but in this case you're on your own.

If there's a possibility of the fields changing order, you might want to break that up into three regexes.