0

I want to extract the three variables (friendCount, pnCount, and allCount) out of a string representation of the following Object:

'{"friendCount":5,"pnCount":0,"allCount":5}'

I thought about using a RegEx or similar, but I have no further Idea. The numbers in the string may be between 0 and about 100

0

3 Answers 3

7

If that is a string, than parse it...

var str = '{"friendCount":5,"pnCount":0,"allCount":5}';
var obj = JSON.parse(str);
console.log(obj.friendCount, obj.pnCount, obj.allCount);

If it is already an object, just reference it

var obj = {"friendCount":5,"pnCount":0,"allCount":5};
console.log(obj.friendCount, obj.pnCount, obj.allCount);
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

var data= {"friendCount":5,"pnCount":0,"allCount":5}

var friendCount = data.friendCount;
var pnCount = data.pnCount;
var allCount = data.allCount;

Comments

0

If you want Regex it can be done like this:

var re = /([\w]+)":(\d+)/g; 
var str = '"friendCount":5,"pnCount":0,"allCount":5';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.