Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting JSON string to JavaScript array

Status
Not open for further replies.

varocho

Programmer
Dec 4, 2000
238
0
0
US
I have some JavaScript that processes data returned from a Web service call:

var jsonObject = eval('obj=' + data);
var result = jsonObject['GetOffices']['offices'];

The value of the 'result' variable is:

[{"streetAddress":"1501 Main Street","phone":"703-123-4567","postalCode":"12345","fax":"703-883-4037","name":"Remote Office #3","state":"VA","poid":"BO^NORA.MIM.Users.Office^2679e3af:126776b793e:-8000","className":"Office","country":"USA","city":"Anytown"}]

How can I convert this string value to a JavaScript array, and then how can I get the value of an attribute, such as 'name'?

 
Given you clearly already know how to use "eval", I'm not sure why you're asking this... but anyway:

Code:
var resultArr = eval(result);
alert(resultArr[0].name);

Dan


Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Hi

And a solution for the future.

In ECMAScript 5[sup]th[/sup] edition there is a [tt]JSON[/tt] object specified for this :
JavaScript:
[b]var[/b] resultArr [teal]=[/teal] JSON[teal].[/teal][COLOR=darkgoldenrod]parse[/color][teal]([/teal]data[teal]);[/teal]
[COLOR=darkgoldenrod]alert[/color][teal]([/teal]resultArr[teal][[/teal][purple]0[/purple][teal]].[/teal]name[teal]);[/teal]
It is implemented in Gecko 1.9.1, Presto 2.4, WebKit ( found no version ). Rumors say that in Trident too.

[tt][blue][small][ignore][off-topic][/ignore][/small][/blue][/tt]
Another reason for the Upgrade your browser ! links...
[tt][blue][small][ignore][/off-topic][/ignore][/small][/blue][/tt]


Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top