Reputation: 623
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?
Upvotes: 0
Views: 279
Reputation: 853
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);
Upvotes: 0
Reputation: 6479
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);
Upvotes: 2
Reputation: 6203
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...
Upvotes: 1