0

I've been trying to use the approach suggested by another SO-User: https://stackoverflow.com/a/1820837/1324861

But without luck. Basically, I have a large JSON Object that I transformed into a string using JSON.stringify() in order to execute a regexp pattern against. My idea is to return everything between { } if my search term "soccer" is found anywhere between the curly braces.

My data could look like this:

{
  {
    User: "Peter",
    Hobbies: "Soccer, Football, ...",
    more...
  },
  {
    User: "Simon",
    Hobbies: "Pingpong, Soccer, Badminton",
    more...
  }
}

So if I searched for 'soccer' in my stringified JSON Object I'd like to get back the entire info on the user. How can I do this?

Community
  • 1
  • 1
opfeffer
  • 603
  • 5
  • 19

4 Answers4

2

You could inspire from this (without transforming your json into string):

var myData = [
  {
    User: "Peter",
    Hobbies: "Soccer, Football, ..."
  },
  {
    User: "Simon",
    Hobbies: "Pingpong, Soccer, Badminton"
  }
];
var results = "";
for (var i = 0; i < myData.length; i++) {
    if (myData[i]["Hobbies"].indexOf("Soccer") != -1) {
        results += JSON.stringify(myData [i]) + "\n";
    }                  
}
alert(results);
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
1

Not that it doesn't make sense to stringify a JSON object to apply a regex on it (shudder) but hey, it's your CPU... You could use something like this:

\{[^{]+soccer[^}]+}

This should catch what you're looking for. But... Parsing JSON with regexes... Nononono...

dda
  • 6,030
  • 2
  • 25
  • 34
  • I'm not very happy with this approach either but it seems about the only one I can come up with because my JSON is dynamic and with variable depths (aka I may have data.cat1.subcat2.items[] and data.cat2.items[]) and I want to search over all items in all cat/subcats. - have more performant ideas how i could achieve that? – opfeffer Jul 24 '12 at 15:47
  • 2
    @opfeffer it doesn't matter what your JSON is, it's always easier, faster and less error-prone to search its object representation – Esailija Jul 24 '12 at 15:48
  • @opfeffer Could you post a sample of your JSON? Maybe just a a couple of elements, with sub and sub-sub elements? – dda Jul 25 '12 at 02:27
0

Something like "{[^}]*(S|s)occer[^}]*}"

Fanny
  • 310
  • 3
  • 4
  • 8
0
var json = [
  {
    User: "Peter",
    Hobbies: "Soccer, Football, ..."
  },
  {
    User: "Simon",
    Hobbies: "Pingpong, Badminton"
  }
];


var jsonString = JSON.stringify(json);
var regEx = /(\{.*?Soccer.*?\})/;
var user = jsonString.match(regEx)[1];
document.write(user);
spats
  • 805
  • 1
  • 10
  • 12