0

I'd like to search only a specific piece of a string and show it using nothing more than JS or Jquery.

For example, (It just looks like a JSON, but it's not, it's just brackets some stuff ;) ):

var data = 
 [{"name":"node1","id":1,"is_open":true,"children":
   [
     {"name":"child2","id":3},
     {"name":"child1","id":2}
   ]
 }];

I'd like to pick up only the ID numbers:

The "code" below is not a language, it's just an example to help understanding what I'd like to do on JS/jQuery

var IDs = [searchThrough] data [where there is] "id": [getContent] after : and before , or } alert("IDs: "+IDs);

It allows me to:

1 - set a parameter of what I want from a string find "id": on data.

2 - set the start and end for getting the content after : and before , or }

How can I do it?

Thanks in advance.

"Beam me up Scotty!"

3
  • @RoryMcCrossan Thanks for pointing out :D, so how can I do it? Commented Jul 28, 2015 at 13:32
  • So, to clarify, you're trying to get all the id properties in the array of objects? Even those on the children? Commented Jul 28, 2015 at 13:33
  • kind of, I edited my question to make it clearer, sorry for not being clear Commented Jul 28, 2015 at 13:36

3 Answers 3

1

I am no regex guru,but this is my try.

var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child1","id":2}]}]';
var arrays=[];
var t1=data.match(/"id":[0-9]+(,|})*/g);
for(var x=0;x<t1.length;x++)
{
  arrays.push(t1[x].match(/\d+/));   

}
alert(arrays);
Sign up to request clarification or add additional context in comments.

2 Comments

I tried yours and it ran smoother, I think I'll be forced to mark yours as the answer
@Calne Appreciate It :) Hope it helped.
1

If I understand you, you want to search a String that represents the data. In this case, you could use a regular expression like the following:

var matcher = /"id":([^,\}]*/g, // capture all characters between "id" and , or }
    match, IDs = [];

while (match = matcher.exec(data)) {
  IDs.push(match[1]);
}

alert(IDs);

1 Comment

Fantastic, that was exactly what I was looking for thanks for helping me :)
1

If we take the assumption that you are dealing with a string, we can pull out the data using regular expression:

var str = '[{"name":"node1","id":1,"is_open":true,"children":\n   [\n     {"name":"child2","id":3},\n     {"name":"child1","id":2}\n   ]\n }];';
var regex = /"id":([0-9]*)/g;
var match = regex.exec(str);

var res = new Array();

while (match != null) {
  res.push(match[1]);
  match = regex.exec(str);
}

var ids = res.join();

alert("IDs: " + ids);

This demo will give you an alert box with the content "IDs: 1,3,2"

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.