2

So I have a json string that Looks like this

var jsonString = '[{"name":"John Smith","uid":1234,{"name":"Susie Something","uid":4567"}]';

I'm making a function that will return all the UIDs seperated by commas. So for example: 1234,4567.

What I do now is this

function getUIDS(json){
var uids = '';
parsed = JSON.parse(json);

$.each(friends, function() {
        uids = uids + this.uid.toString() + ',';
 });
 reuturn uids;

}

However, nothing returns. How can I access a variable that was created by a jquery thread, outside of the jquery thread.

3
  • 1
    First, your jsonString is not well-formed. Commented Jun 27, 2012 at 7:36
  • 2
    Maybe nothing returns because of reuturn? Furthermore, check the JSONstrings. Third, you should parse the JSON before you can use it as an object. Commented Jun 27, 2012 at 7:36
  • Fourth, you're iterating over friends (which is not defined), not parsed. Commented Jun 27, 2012 at 7:40

3 Answers 3

1

Pass parsed instead of friends, if this is complete code and friends is not defined anywhere

function getUIDS(json){
var uids = '';
parsed = JSON.parse(json);

$.each(parsed, function() {
        uids = uids + this.uid.toString() + ',';
 });
 reuturn uids;

}
Sign up to request clarification or add additional context in comments.

Comments

1

Try fixing your json:

var jsonString = '[{"name":"John Smith","uid":1234},{"name":"Susie Something","uid":4567"}]';

And change your code slightly:

function getUIDS(json) {
   var uids = '',
       friends = JSON.parse(json);

   $.each(friends, function() {
       uids += this.uid + ',';
   });

   return uids;
}

The important parts are looping over friends and spelling return correctly.

You should also consider using join as suggested by someone. That will make sure you don't get a trailing "," at the end of your uids string (unless that's what you want).

Comments

0

Try:

function getUIDS(json){
  var uids = [];
  var friends = JSON.parse(json);

  $.each(friends, function(i) {
     uids.push(friends[i].uid);
  });

  return uids.join(',');
}

Problems in your code were: (See code comments)

function getUIDS(json){
var uids = '';
parsed = JSON.parse(json);

$.each(friends, function() { // using friends instead of parsed
        uids = uids + this.uid.toString() + ','; // using this here
 });
 reuturn uids; // spelling mistake for return keyword

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.