JSignage:Parsers

From SpinetiX Support Wiki

Jump to: navigation, search

This page describes jSignage utility methods for parsing text content.

Introduction

The purpose of the jSignage parsers is to transform a plain text response of a AJAX call (get / post) into a structured representation that can be easily used afterwards by other jSignage / JavaScript functions.

There are several parsers available in jSignage for common text formats, for everything else you can use the JavaScript built-in regular expressions engine.

XML parser

$.parseXML(text)

Parameters:

  • text
    String containing the XML code.

Returns a document DOM object or null if the text is not valid XML. The top level element is the .documentElement property of the returned object.

Example:

var doc = $.parseXML( '<top><child/></top>' );
alert( 'top level is: ' + doc.documentElement.localName );
alert( 'first child is: ' + doc.documentElement.firstElementChild.localName );

JSON parser

JSON is a very efficient and convenient format for getting data from web server scripts (e.g., a PHP script front-end to a database).

$.parseJSON(text)

Parameters:

Returns a JavaScript object / array corresponding to the JSON text.


Note Notes:
  • Passing a malformed JSON string does not throw a JavaScript exception, as is the case in jQuery.
  • If the dataType is not explicitly specified as 'text' when calling the $.get() or $.post() methods and the mime type returned by the server indicates a JSON object, the result is automatically parsed into a JavaScript object, so there's no need to call $.parseJSON() in this case.

Example:

var item = $.parseJSON('{ "label": "ultimate gadget", "price": 19.99 }');
alert( 'label: '+item.label );
alert( 'price: '+item.price );

RSS feed parser

$.parseRSS(text[, baseURI, channel, multilineTitle])

Parameters:

  • text
    Unparsed RSS feed content.
  • baseUri
    Base URI to use in case the feed contains relative links. By default the links stay relative.
  • channel
    Identifier that selects only one channel in the feed. Must be equal to the <link> value in the channel. By default all items for all channels are returned.
  • multilineTitle
    Allow the titles to contain more than one line. By default only the first line is returned.

Returns a JavaScript array of objects, where each object has the following properties:

  • title
    Cleaned up content of the <title> element.
  • description
    Cleaned up content of the <description> element.
  • enclosure
    value of the url attribute of the first <enclosure> or <media:content> element if there is one or of the src attribute of the first <img> element inside the description.
  • pubDate
    content of the <pubDate> element as a Date object.
  • channel
    Value of the <link> element that identifies the channel.
  • channelTitle
    Value of the <title> element for the channel.
  • channelDescription
    Value of the <description> element for the channel.
  • image
    Value of the <image> element for the channel.

Note that the clean up process for the title and description attributes includes stripping all HTML tags and converting any HTML entity into the corresponding Unicode character, so that the strings are plain text.

iCalendar parser

$.parseICAL(text, start, end[, maxItems, format])

Parameters:

  • text
    Content of an iCalendar file as a string.
  • start
    JavaScript Date object or number of ms since Jan 1st, 1970 UTC.
  • end
    JavaScript Date object or number of ms since Jan 1st, 1970 UTC.
  • maxItems
    Maximum number of items to return. Default: 100.
  • format
    Optional formatting string for returning dates as strings using the UNIX strftime syntax. Default: dates are returned as Date objects.

Returns a JavaScript array of objects, where each object has the following properties:

  • title
    Event summary
  • description
    Event description
  • startDate
    Start date a Date object or a string according to format argument.
  • endDate
    End date as a Date object or a string according to format argument.
  • enclosure
    URL associated with the event.
  • location
    Event location

The number of returned objects is equal to the number of occurrences of events starting during the selected period, including occurrences due to recurring events. The array is sorted by start date.

Examples

See also the JSignage:Examples page.

Soft Scheduling (1)

// This sample will read an ICS file and find the event that is currently valid. 
// The media associated with this event will play forever.
$.get( 'calendar.ics',
   function( data ) {
      var now = new Date();
      // get one item valid now.
      var schedule = $.parseICAL( data, now.getTime(), now.getTime()+1, 1 ); 
      if ( schedule.length>0 ) {
         // one valid event found, display the media in full screen
         // Play the media forever
         $.media( { href: schedule[0].enclosure, repeatCount: 'indefinite' } ).addTo('svg'); 	
      } else {
         // no event found, we display a warning.
         $.headlineTextArea( {scaleMethod: 'uniform'} ).text('No event found').addTo('svg');
      }
   },   'text'
 );

Soft scheduling (2)

// This sample will read an ICS file and find the event that is currently valid. 
// The media associated with this event will play once and then the document will be stopped.
$.get( 'calendar.ics',
   function( data ) {
      var now = new Date();
      // get one item valid now.
      var schedule = $.parseICAL( data, now.getTime(), now.getTime()+1, 1 ); 
      if ( schedule.length > 0 ) {
         // one valid event found, display the media in full screen
         // play the media once, and then end the current document
         $.media( {href: schedule[0].enclosure } ).endEvent( function() {
            $('svg').attr('dur', $('svg')[0].getCurrentTime() ); // set the duration of the document to the current time.
         }).addTo('svg'); 	
      } else {
         // no event found, we end the document
         $('svg').attr('dur', $('svg')[0].getCurrentTime() + 0.01 ); // to avoid a duration of 0s, which is not valid
      }
   },   'text'
 );

CSV parser

$.parseCSV(text[, separator, columns, keepNSWSP, keepQuotes])

Parameters:

  • separator
    Character used to separate the records in a row. Default: ',' (comma).
  • columns
    Optional array of column names.
    CSV files usually specify the column names on the first row.
    The default behavior is to extract the column names from the top row and discard the top row.
    When columns is specified, it is assumed the top row contains data instead. It should be discarded by the caller if this is not the case, such as when used for overriding the column names.
  • keepNSWSP
    When true, the leading and trailing whitespace characters of an unquoted column (which are normally discarded), are returned.
    Default: false.
  • keepQuotes
    When true, double quotes are not processed as special characters.
    Default: false.

Returns an array of JavaScript objects, where each object corresponds to a row of data.

Multi-line text parser

$.parseTXT( text ) returns an array of JavaScript strings.

Parameters:

  • text
    String containing usually multiple lines of text.

Returns an array containing each line of text.

Regular expressions

JavaScript includes a powerful regular expressions engine via the RegExp class, which can be used for simple text formats using the RegExp.exec() or String.split() methods on the returned content.

RegExp.exec()

result = regexp.exec(str)

Executes a search for a match in a specified string. Returns a result array or null.
For more details, see the RegExp.exec page.

Example:

Assuming that a server script returns a simple data format with each line of text containing a key and a value (enclosed in quotes) separated by the equal sign, for instance:

 name = "Double Espresso"
 price = "2.99"
 description = "This packs enough power to wake up an elephant!"

the typical code for requesting and parsing this type of content into a JavaScript object (i.e. key / value pairs) is the following:

$.get( 'queryDB.php', function( content ) {
   var re = /(\w+)\s*=\s*\"([^\"]*)\"/g;
   var match;
   var item = new Object;
   while ( (match = re.exec( content )) != null ) {
     item[ match[1] ] = match[2];
   }
});

The data can now be accessed conveniently as properties of the object like item.name and item.price.

String.split()

string.split([separator][, limit])

Splits a String object into an array of strings by separating the string into substrings.
For more details, see the String.split page.

Example:

The code to create a scrolling ticker for which the content is loaded from a text file, would be the following:

$.get( 'ticker_of_the_day.txt', function( content ) {
   $.textTicker({
     data: content.split( /\n+/ ),
     repeatCount: 'indefinite',
     top: '80%',
     height: '15%'
   }).addTo('svg');
});

See also

This page was last modified on 21 February 2023, at 19:28.