0

I have a problem... I have the following variable (type: string): {"friendCount":5,"pnCount":0,"allCount":5}

My goal is it, to have 3 variables with friendCount, pnCount and allCount and i don't know, how I can do this. This looks as an object, but it's only a string (planned)

I think that I have to do it with RegEx or something but I have no further Idea...

The numbers in the string may be between 0 and about 100

I hope, that you understand my problem and can help me :)

Gykonik
  • 330
  • 1
  • 3
  • 11
  • 2
    Possible duplicate of [Safely turning a JSON string into an object](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Andrey Korneyev Jan 21 '16 at 14:42

3 Answers3

6

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);
epascarello
  • 195,511
  • 20
  • 184
  • 225
1

Try this

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

var friendCount = data.friendCount;
var pnCount = data.pnCount;
var allCount = data.allCount;
Anoop LL
  • 1,508
  • 2
  • 20
  • 31
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.

}

Aferrercrafter
  • 199
  • 1
  • 5
  • 14