Как искать в JSON с помощью регулярных выражений

1

Я немного потерялся в упражнении, которое я делал сегодня днем. У меня есть информация в массиве JSON, например:

var json = [
  {
    "recipe": {
      "URL": "www.google.com",
      "Title": "theTitle",
      "Time": "theTime",
      "Ingredients": "... tomato potato orange ...",
      "Image": "theImage"
    }
  },
    {
    "recipe": {
      "URL": "www.google.com",
      "Title": "theTitle",
      "Time": "theTime",
      "Ingredients": "... tomato orange potato and fish...",
      "Image": "theImage"
    }
  },
   {
    "recipe": {
      "URL": "www.google.com",
      "Title": "theTitle",
      "Time": "theTime",
      "Ingredients": "... nothing ...",
      "Image": "theImage"
    }
  },
   {
    "recipe": {
      "URL": "www.google.com",
      "Title": "theTitle",
      "Time": "theTime",
      "Ingredients": "... nothing ...",
      "Image": "theImage"
    }
  }
]

И я пытаюсь получить позицию в JSON, если она совпадает с одной из моих переменных. Вот пример того, что я пытаюсь сделать:

var matches = ["tomato","potato"]

for (var i = 0; i < json.length;i++){
if (json[i].recipe.Ingredients == matches) {
alert("I got something :" + json[i])
}
else {
nothing}
}

Поэтому я попытался с помощью регулярного выражения, но это не сработало. Любая идея, как я должен это делать? Извините, если это может показаться глупым, я все еще новичок в кодировании: D!

  • 0
    Вы можете увидеть, существует ли подстрока в другой с помощью String.prototype.indexOf ()
  • 0
    Вы должны решить эту задачу с RegExp ? Я думаю, что это не подходит.
Теги:

3 ответа

2
Лучший ответ

Решением может быть:

new RegExp(matches.join('|')).test(json[i].recipe.Ingredients)

где:

  1. matches.join('|') → "томатный картофель"

  2. новый RegExp (matches.join('|')) ->/tomato | potato/(regex)

  3. json [i].recipe.Ingredients → - это содержимое ингредиентов

  4. test - метод выполняет поиск совпадения между регулярным выражением и указанной строкой. Возвращает true или false.

var json = [
    {
        "recipe": {
            "URL": "www.google.com",
            "Title": "theTitle",
            "Time": "theTime",
            "Ingredients": "... tomato potato orange ...",
            "Image": "theImage"
        }
    },
    {
        "recipe": {
            "URL": "www.google.com",
            "Title": "theTitle",
            "Time": "theTime",
            "Ingredients": "... tomato orange potato and fish...",
            "Image": "theImage"
        }
    },
    {
        "recipe": {
            "URL": "www.google.com",
            "Title": "theTitle",
            "Time": "theTime",
            "Ingredients": "... nothing ...",
            "Image": "theImage"
        }
    },
    {
        "recipe": {
            "URL": "www.google.com",
            "Title": "theTitle",
            "Time": "theTime",
            "Ingredients": "... nothing ...",
            "Image": "theImage"
        }
    }
];
var matches = ["tomato", "potato"]

for (var i = 0; i < json.length; i++) {
    if (new RegExp(matches.join('|')).test(json[i].recipe.Ingredients)) {
        console.log("I got something :" + JSON.stringify(json[i]))
    }
    else {
        console.log('nothing');
    }
}
0

Спасибо вам обоим ! Последний вопрос, мой JSON получит около 60 тыс. Предметов. Как вы думаете, я могу остановиться на этих методах поиска или мне абсолютно необходимо создать API?

0

Вот мое решение без использования Regex.

var json = [
  {
    "recipe": {
      "URL": "www.google.com",
      "Title": "theTitle",
      "Time": "theTime",
      "Ingredients": "... tomato potato orange ...",
      "Image": "theImage"
    }
  },
    {
    "recipe": {
      "URL": "www.google.com",
      "Title": "theTitle",
      "Time": "theTime",
      "Ingredients": "... tomato orange potato and fish...",
      "Image": "theImage"
    }
  },
   {
    "recipe": {
      "URL": "www.google.com",
      "Title": "theTitle",
      "Time": "theTime",
      "Ingredients": "... nothing ...",
      "Image": "theImage"
    }
  },
   {
    "recipe": {
      "URL": "www.google.com",
      "Title": "theTitle",
      "Time": "theTime",
      "Ingredients": "... nothing ...",
      "Image": "theImage"
    }
  }
]


var matches = ["tomato","potato"]

for (var i = 0; i < json.length;i++){
  matches.forEach(function(word){
   if(json[i].recipe.Ingredients.indexOf(word) > -1){
     console.log(json[i]);
   } else {
    console.log("doesn't exist");
   }
  });
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню