JavaScript code - UNIX grep command?

Discussion in 'JavaScript' started by simpsa30, Nov 11, 2019.

  1. #1
    Hi

    I am new to JavaScript & haven't done much work with it, but have mainly experience with UNIX. I have a piece of code where I want to grep (excuse the UNIX language [​IMG]) for a id and get the number from that.

    {
    "time": 900,
    "avail": 1,
    "price": 0,
    "datetime": "2019-11-09T15:00:00+00:00"
    }
    {
    "name": "janice-bishop",
    "date": "2019-11-09",
    "event_ID": 155643,
    "person_ID": 18709,
    "resource_ID": 561,
    "_links" :
    }
    Code (javascript):


    I am essentially looking for something which would be
    if avail = 1
    then
    grep event_ID

    & then want to print the number which would be the event id? Not sure how possible this is within JavaScript but something along those lines like you would do with a UNIX shell script.
     
    Last edited by a moderator: Nov 11, 2019
    simpsa30, Nov 11, 2019 IP
  2. hdewantara

    hdewantara Well-Known Member

    Messages:
    538
    Likes Received:
    47
    Best Answers:
    25
    Trophy Points:
    155
    #2
    If only that string were convertable to one valid JSON object (not two) e.g.
    var str = '{"time": 900,"avail": 1,"price": 0,"datetime": "2019-11-09T15:00:00+00:00", "name": "janice-bishop", "date": "2019-11-09", "event_ID": 155643, "person_ID": 18709, "resource_ID": 561, "_links": ""}';
    Code (JavaScript):
    then we can easily execute:
    var json = JSON.parse(str);
    if(json.avail === 1) alert(json.event_ID);
    Code (JavaScript):
     
    hdewantara, Nov 11, 2019 IP
  3. simpsa30

    simpsa30 Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #3
    Hi hdewantara

    So this is run as an API & the value would be dynamic as in won't always be 155643 so that will change every time it runs?
     
    simpsa30, Nov 11, 2019 IP
  4. hdewantara

    hdewantara Well-Known Member

    Messages:
    538
    Likes Received:
    47
    Best Answers:
    25
    Trophy Points:
    155
    #4
    Yes it will, why don't you try testing it :)
    But I guess the problem is the original return string of the API... it must be a valid JSON string or else should be converted to a valid string. You may want to validate it through this link: https://duckduckgo.com/?q=json+validator&t=ffab&ia=answer
     
    hdewantara, Nov 11, 2019 IP