Thursday, 15 September 2011

javascript - how can I parse json with multiple lines -



javascript - how can I parse json with multiple lines -

i have next json:

[{"returncode":"0","errormessage":"success","code":{},"phonenumber":"400557704","mobile":"400089151"}, {"returncode":"0","errormessage":"success","code":{},"phonenumber":"400557705","mobile":"400089151"}, {"returncode":"0","errormessage":"success","code":{},"phonenumber":"400557706","mobile":"400089151"}, {"returncode":"0","errormessage":"success","code":{},"phonenumber":"400557707","mobile":"400089151"}]

i need extract "phonenumber" using js function. i'm testing using html , function not good:

function getnumbers(strjson) { strjson = "[{\"errormessage\":\"success\",\"mobile\":\"400089151\",\"phonenumber\":\"400557704\",\"returncode\":\"0\"},{\"errormessage\":\"success\",\"mobile\":\"400089151\",\"phonenumber\":\"400557705\",\"returncode\":\"0\"},{\"errormessage\":\"success\",\"mobile\":\"400089151\",\"phonenumber\":\"400557706\",\"returncode\":\"0\"}]"; var len = strjson.length; var begin_index = strjson.indexof("returncode") - 2; var last_index = len - 1; var string_tosplit = strjson.substring(begin_index, last_index); var string_splitted = string_tosplit.split("{"); var out=""; alert(strjson); alert("string_splitted"); alert(string_splitted); ( var = 0; < string_splitted.length; i++) { if (string_splitted[i].charat(string_splitted[i].length - 1) === ",") { string_splitted[i] = string_splitted[i].slice(0, -1); } var json = "{" + string_splitted[i]; var obj = json.parse(json); if (i == string_splitted.length) { out = out + obj.phonenumber; } else { out = out + obj.phonenumber + ","; } } homecoming out; }

for modern browsers can utilize .map() method

var j = [{"returncode":"0","errormessage":"success","code":{},"phonenumber":"400557704","mobile":"400089151"}, {"returncode":"0","errormessage":"success","code":{},"phonenumber":"400557705","mobile":"400089151"}, {"returncode":"0","errormessage":"success","code":{},"phonenumber":"400557706","mobile":"400089151"}, {"returncode":"0","errormessage":"success","code":{},"phonenumber":"400557707","mobile":"400089151"}]; var phones = j.map(function(item){return item.phonenumber});

update

after seeing code (do not seek manually split/parse json string.. utilize json.parse method) should use

function getnumbers(strjson) { var myjson = json.parse( strjson ); homecoming myjson.map(function( item ){ homecoming item.phonenumber}).join(','); }

javascript json

No comments:

Post a Comment