Skip to main content
4 of 4
deleted 192 characters in body

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 clearly that's not a possibility here.

In cases where you can trust your source to keep cranking out this stuff in the same format for at least the near future, it's safe to fall back on an ugly regex solution -- just make sure it can handle every case the source may produce:

function parseCompany(str) { var re = /name:\s*([^,]+),\s*price:\s*(-?[\d\.]+|#N\/A),\s*change:\s*(-?[\d\.]+|#N\/A)/; 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.

UPDATE: Added "#N/A" handling for price and change. If those values are "#N/A", they'll will come out as NaN, JavaScript's magic "not a number" value.