JavaScript Objects, Methods, and Variables Reference

As you add JavaScript within your execute sub-element, you can take advantage of the following global objects:

Object Description
y Global object that provides access to additional language capabilities.
request The request object is a global reference to the rest object that contains the URL on which YQL would normally perform a GET request. You cannot reference the rest object directly, so you need to use request or y.rest to access the rest object.
response Response object returned as part of the "results" section of the YQL response.

Let's discuss each of the global objects in detail.

y Global Object

The y global object contains methods that provide basic YQL functionality within JavaScript. It also allows you to include YQL Open Data Tables and JavaScript from remote sources.

Method/Property Description Returns
cache The cache object provides access to methods for caching. JavaScript object
context Provides information about the context or environment that JavaScript code is running in. JavaScript object
context.host The name of the host server that is executing the YQL statement. string
context.table The name of the Open Data Table where JavaScript within an execute element is running. string
crypto Provides basic cryptographic functions for use within JavaScript. Example:

var md5string = y.crypto.encodeMd5("encode this string to md5");

Encrypted string
date Provides access to date-related functions. JavaScript object
decompress(base64_compressed_string) Decodes a base64 string and then decompresses that string with gunzip. This method allows you to decompress the POST request body and query parameters. string
deflate(string, level) Deflates a string at the specified compression level and then Base64-encodes the result. Base64-encoded and compressed string
diagnostics Returns diagnostic information related to the currently executed script. Diagnostic information
env(environment file) Includes an environment file for use with your JavaScript. Example:

y.env("http://datatables.org/alltables.env");

-
exit(), exit(status_code,msg) Stops the execution of the current script. -
include(url) Includes JavaScript located at a remote URL. Returns an evaluation of that include.
inflate(base64_deflated_string) Decodes a Base64-encoded compressed string and then inflates it. string
log(message) Creates a log entry in diagnostics. Returns the log entry within the diagnostics output associated with the current select statement
query(statement,params, timeout, callback) Prepares and runs a YQL statement. Execute will replace all @name fields in the YQL statement with the values corresponding to the name in the supplied hash table. Creates a result instance, or returns an error.
rest(url, callback) Sends a GET request to a remote URL endpoint. -
sync(flag) Defers the JavaScript execution until pending asynchronous requests have been completed. -
tidy (html) Tidy and return provided HTML. HTML that is run through HTML Tidy.
use(url,namespace) Imports an external Open Data Table definition into the current script at runtime. -
xpath(object,xpath) Applies XPath to an E4X object. E4X object

Conversion Methods

Method/Property Description Returns
jsonToXml(json_obj) Converts a JavaScript/JSON object into E4X/XML. E4X object
jsToString(json_object) Converts a JSON object to a string. string
xmlToJson(object) Converts an E4X/XML object into a JSON object. JavaScript object
xparseJson(json_str) Returns a JavaScript object when given a well-formed JSON string. JavaScript object
y.crypto functions

YQL provides several cryptographic functions for use within JavaScript. These functions reduce the need for external libraries and make YQL easier to use.

Examples:

Function Description Returns
encodeHmacSHA256(String secret, String plaintext) Encrypts a string using HMAC-SHA256 encryption. Returns an encrypted string.
encodeHmacSHA1(String secret, String plaintext) Encrypts a string using HMAC-SHA1 encryption. Returns an encrypted string.
encodeMd5(String plaintext) Provides the MD5 hash of a string. Returns an MD5 hash of a BASE64-encoded string.
encodeMd5Hex(String plaintext) Provides the MD5 hash of a hex-encoded string. Returns an MD5 hash
encodeSha(String plaintext) Provides the SHA-1 hash of a string. Returns an SHA-1 hash.
encodeBase64(String plaintext) Performs Base64 encoding of a string. Returns an Base64 encoded string.
decodeBase64(String plaintext) Performs Base64 decoding of a string. Returns an Base64 decoded string.
uuid() Provides a cryptographically secure version 4 Universal Unique Identifier (UUID). Returns a UUID.
y.date

Using y.date gives you access to date-related functions.

Methods
y.date.getOffsetFromEpochInMillis(time_format)

Parses the given date string in a format specified by RFC 3339 and returns the number of milliseconds since the Unix epoch (0:00:00 UTC on January 1, 1970) as a string.

Parameters:

  • time_format <String> A string in the form of the time/date formats or regex patterns below. The regex patterns are case insensitive.

    • RFC 3339 Timestamp
    • ^([+-])?\s*(\d+)\s*(year|month|week|day|hour|minute)s?$
    • ^(\d+)\s*(year|month|week|day|hour|minute)s?\s+(from\s+now|after|after\s+today|later|old|ago)$
    • ^now\s+([+-])\s*(\d+)\\s+(year|month|week|day|hour|minute)s?$
    • ^last\s+(year|month|week)$
    • now
    • yesterday
    • tomorrow

Returns: String

Examples:

In the example table below, getOffsetFromEpochInMills is used in conjunction with the JavaScript Date object to log several different times. The table then returns the execution time of the JavaScript in the response.

In this example XML response returned by the above table, the diagnostic information includes the logged times, and the result element contains the execution time.

y.decompress(base64_compressed_string)

Allows you to decompress query parameters and the HTTP POST request body. The decompress method decodes a base64 string and then uses gunzip to decompress the string.

Parameters:

  • base64_compressed_string <String> A string that has been compressed with gzip and then base64 encoded.

Returns: String

Examples:

YQL Statement: use 'http://example.com/decompress.xml' as decompress; select * from decompress where foo="H4sIAOQTlU0AA8tIzcnJBwCGphA2BQAAAA=="

Example YQL Open Data Table: http://example.com/decompress.xml

The table decompress.xml below uses y.decompress to decompress the value assigned to foo in the YQL statement above and then returns it as the string.

Returned XML Response:

y.deflate(string, level)

Deflates the given string into a zlib format at the specified compression level and then Base64-encodes the result.

Parameters:

  • string <String> - The input string to compress.
  • level <Number> - The compression level. See Class Deflater for the list of supported compression levels.

Returns: String

Examples:

In the example below, data is compressed with y.deflate and then posted to a Web service with y.rest.

y.exit(), y.exit(status_code,msg)

Causes the script to exit. If no parameters are given to y.exit, the YQL engine returns the default HTTP response status code and message to the client. The table author can change the HTTP response code sent to the client by passing a status code and a message as parameters to y.exit.

Parameters:

  • status_code <Number> - The HTTP response status code that gets returned to the client.
  • msg <String> - The message that gets returned to the client.

Returns: None

Example:

y.getTenantContextsAvailable()

Gets the names of all the tenants with configurations that can be used to create execution contexts for the query, env, and use methods. The returned tenant names will be the same, or super set, of the names returned by y.getTenantContextsAllowed.

Parameters: None

Returns: Object

Examples:

The following example table returns all of the available tenant contexts.

y.inflate(base64_deflated_string)

Decodes the given Base64-encoded compressed string and and then inflates it.

Parameters:

  • base64_deflated_string <String> - The input string to decode and inflate.

Returns: String

Examples:

In the example below, a Base64-coded and deflated string is passed as a query string parameter to the YQL Web Service URI. The table decodes and inflates the data, processes the inflated data, and then posts the data to the Web service.

y.jsonToXml(json_object)

Converts a JSON object into its equivalent XML (E4X) object.

Parameters

  • json_object <Object> A JSON object.

Returns: E4X object

y.jsToString(json_object)

Converts a JSON object into its equivalent JSON string form.

Parameters:

  • json_object <Object> A JSON object.

Returns: String

y.query(statement, params, timeout, callback)

Perhaps you want to use YQL queries while still using JavaScript within YQL. y.query allows you to perform additional YQL queries within the execute sub-element.

Parameters:

  • statement <String> A YQL statement.
  • params <Object> The object can contain key-values that can be referenced in the YQL statement for variable substitution. In the example below, the @query, @cat_id, and @type variables are passed to the YQL statement and replaced with the values associated with the keys of the params object.
  • timeout <Number> The number of milliseconds before the call times out.
  • callback <Function> The callback function to handle the returned response. See Making Asynchronous Calls with JavaScript Execute for more information about using the callback.

Returns: Object

The returned object contains the following properties:

Property Description Data Type
diagnostics The diagnostic information associated with the request. E4X object
format Allows you to request results to be returned as JSON or XML. The default format is XML. function
query The YQL statement that was passed as a parameter to y.query. string
results The results returned by the query. E4X object
timeout

Specifies the request timeout in milliseconds. This is useful when you want to cancel requests that take longer than expected.

None

Examples:

In the following code snippet that we looked earlier, y.query executes a statement that uses the answers.search table to get answers for questions regarding cars. The results are returned in the default format XML.

Using the format method, you can have the results returned in JSON:

y.rest(url [, callback])

The y.rest method allows you to make GET requests to remote Web services. It also allows you to pass parameters and headers in your request and use a callback function to make asynchronous requests. See Making Asynchronous Calls with JavaScript Execute for more information about using the callback.

Parameters:

  • url <String> The URL endpoint to a query.
  • callback <Function> (Optional) The callback mechanism waits to receive returned results that it can then process. This callback function allows asynchronous calls because the function can wait for the returned results while y.rest is called again.

Returns: rest Object

Examples:

In the following code snippet, an HTTP GET request is made to example.com and the response is saved to data.

The two properties url and timeout of the response help you determine if a call has timed out or associate the response with the original URL. The code snippet below show you the url and timeout properties and how you could potentially use them:

Tip

The y.rest method supports "chaining", which means that you can construct and run an entire REST request by creating a "chain" of methods. Here is a hypothetical example:

When chained, the resulting request looks like this:

Note

Because JSON does not have a "root" node in most cases, all JSON responses from a remote Web service will be contained within a special json root object under response.results.

y.sync(flag)

Causes the JavaScript execution to wait until pending y.rest and y.query asynchronous requests have been completed. If asynchronous y.rest and y.query requests refer to a JavaScript callback function, then y.sync should be called to ensure that JavaScript execution does not complete before all the asynchronous requests have completed and before callback functions have been invoked.

Returns true if there are no more asynchronous operations pending, otherwise returns false.

Parameters:

  • flag <Boolean> If true, y.sync will block until all asynchronous operations have completed. Otherwise, y.sync will block until any one of the pending asynchronous operations have either completed, timed out, or produced errors.

Returns: Boolean

Examples:

See Making Asynchronous Calls with JavaScript Execute for examples.

y.xmlToJSON(e4x_obj)

Converts a E4X object into its equivalent JSON string form.

Parameters:

  • e4x_object <Object> An E4X object.

Returns: String

y.xparseJson(json_str)

Parses a well-formed JSON string and returns the resulting JavaScript object. If given a malformed JSON string, y.xparseJson will throw a runtime JSONException.

Parameters:

  • json_str <String> A well-formed JSON string.

Returns: Object

Examples:

The table below parses a JSON string and returns a string value from one of the properties of the created JavaScript object.

Example XML Response:

request Global Object

The request global object is essentially a reference to a rest object. You must use the request object, y.rest, or y.query to access the rest object.

rest Object

The rest object has properties and methods for getting information and making REST calls.

Properties
Property Description Data Type
headers Gets the hashmap of headers object
url Provides a URL endpoint to query string
queryParams Gets the hashmap of query parameters E4X object containing query parameters.
matrixParams Gets the hashmap of matrix parameters result object containing matrix parameters.
Methods

The rest object contains methods that provide basic YQL functionality within JavaScript.

Method Description Returns
accept(content-type) Specifies the type of content to send in the response using the Accept HTTP header. rest Object
decompress(bool) Configures REST call to decompress the returned response with gunzip. rest Object
del() Performs an HTTP DELETE. rest Object
fallbackCharset(charset_list) Overrides the list of fallback character sets, which is set to "utf-8, iso-8859-1" by default, for decoding the returned response. rest Object
filterChars(filter_list) Removes illegal characters from the response data based on specified encoding standards. rest Object
forceCharset(charset_list) Decodes the response using the first successful character set listed in charset_list. rest Object
get() Performs a GET request to the URL endpoint. result Object
head() Performs an HTTP HEAD request on a URL. JavaScript object
jsonCompat(mode) Allows you to get "lossless" JSON when making a REST call to a Web service. rest Object
matrix(name,value) Adds a matrix parameter to the request. rest Object
path(path_segment) Appends a path segment to the URI. request Object
post(content) Performs an HTTP POST, using the value of the content, to the URL endpoint. result Object
put(content) Performs an HTTP PUT, using the value of the content, to the URL endpoint. result Object
query(key, value) Adds a single query parameter. request Object
query(hashmap) Adds all the query parameters based on key-name hashmap. request Object
timeout(milli_seconds) Specifies the request timeout in milliseconds. None
accept(content-type)

Specifies the type of content to send in the response using the Accept HTTP header. This tells YQL what kind of data format you want returned, as well as how to parse it.

Parameters:

  • content-type <String> The content type of the data being sent. For example: application/xml.

Returns: rest Object

Examples:

The following is an example of how you would specify JSON as the return format for data you send as XML:

Using the above example, YQL will convert XML to JSON prior to returning it in the response.

contentType(content-type)

Specifies the content-type of the data being sent. An example of a content-type is: application/json. This object is useful with INSERT and UPDATE statements.

Note

This method does not automatically convert one data format to another prior to sending it, so if you indicate one format in contentType but actually send another, your Web service may produce an error.

Parameters:

  • content-type <String> The content-type of the data being sent. An example of a content-type is: application/json.

Returns: rest Object

The following is an example of how you would specify XML as the data you are sending:

del()

Performs an HTTP DELETE. This object is useful with DELETE statements.

Parameters: None

Returns: result Object

Examples:

In the below Open Data Table, the del() method is used to delete the Mixi voice status identified by the post ID. Using del() sends an HTTP DELETE request to the URL defined in the url element.

fallbackCharset(charset_list)

Overrides the list of fallback character sets, which is set to "utf-8, iso-8859-1" by default, for decoding the returned response. YQL attempts to decode the response using the character sets listed in charset_list when the response either does not specify the character set or specifies an incorrect character set that results in a failed decoding.

Parameters:

  • charset_list <String> A list of one or more fallback character sets. For example: "ISO-8859-1, utf-8"

Response: rest Object

Examples:

filterChars(filter_list)

The filterChars(filter_list) method removes illegal characters from the response data based on the encoding standards passed as arguments.

Parameters:

  • filter_list - A string that contains one to three of the encodings listed below. The encodings are comma delimited, such as "encoding, xml, json".
    • encoding - removes any character that does not conform to Web service character encoding.
    • xml - removes any character that does not conform to the XML standard where conforming XML characters are are represented by c in the following list:
      • c == 0x09
      • c == 0x0A
      • c >= 0x20 && c <= 0xD7FF
      • c >= 0xE000 && c <= 0xFFFD
      • c >= 0x10000 && c <= 0x10FFFF
    • javascript - removes any character that does not conform to the JavaScript standard where non-conforming JavaScript characters are represented by c in the following list:
      • c == 0x0000 || c == 0x00ad
      • c >= 0x0600 && c <= 0x0604
      • c == 0x070f || c == 0x17b4 || c == 0x17b5
      • c >= 0x200c && c <= 0x200f
      • c >= 0x2028 && c <= 0x202f
      • c >= 0x2060 && c <= 0x206f
      • c == 0xfeff
      • c >= 0xfff0 && c <= 0xffff

Response: rest Object

Examples:

forceCharset(charset_list)

Forces YQL to decode the response using the first successful character set listed in charset_list. Using this method overrides both the character set specified by the response and the fallback character sets.

Parameters:

  • charset_list <String> A list of one or more character sets that YQL will use to decode the response. For example: "ISO-8859-1, utf-8"

Returns: rest Object

Examples:

get()

Performs a GET request to the URL endpoint. This object is useful with SELECT statements.

Parameters: None

Returns: result Object

Examples:

head()

Performs an HTTP HEAD request on a URL.

Parameters: None

Returns: Object

Examples:

The head method in this example table is used to make an HTTP HEAD request. The HTTP header fields in the returned object are accessed with the headers property.

header(name, value)

Adds an HTTP header to the request.

Parameters:

  • name <String> The name of the HTTP header.
  • value <String> The value associated with the HTTP header.

Returns: rest Object

Examples:

The headermethod in this code snippet is used to pass authorization credentials to get a response.

In this code snippet, the header method sets the HTTP header Content-Encoding to gzip, so that the returned response will be compressed.

jsonCompat(mode)

Allows you to get "lossless" JSON when making a REST call to a Web service. For more information about "lossy" JSON, see JSON-to-JSON Transformation and Preventing Lossy JSON Results.

Parameters:

  • mode <String> Currently, the only allowed value is "new". In the future, other modes of lossless JSON compatibility might exist that require passing a different string to jsonCompat.

Returns: rest Object

Examples:

The table below makes two GET calls to the Yahoo Upcoming API. The first call returns lossy JSON, and the second call returns lossless JSON. You can view the difference in the returned JSON in the diagnostic logs.

Note that to obtain lossless JSON when querying the above table, the client must append the query string parameter jsonCompat=new to the YQL URI as shown here:

http://query.yahooapis.com/v1/public/yql?q=use 'http://example.com/jsonCompat.xml as json.compat; select * from json.compat&format=json&jsonCompat=new

matrix(name,value)

Adds a matrix parameter to the request.

Parameters:

  • name <String>
  • value <String>

Returns: rest Object

Examples:

The code snippet below posts the matrix parameters to flower_order_server.com.

Matrix parameters are attached to the URI resource like query parameters, but are delimited by a semicolon and not an ampersand and the matrix parameters are not separated from the URI resource by a question mark. The yql.rest call creates the following URL: http://flower_order_service.com;flower=roses;color=red

path(path_segment)

Appends a path segment to the URI.

Parameters:

  • path_segment <String> The path segment to add to a URI.

Returns: request Object

Examples:

post(content)

Performs an HTTP POST, using the value of the content, to the URL endpoint. This object is useful with INSERT, UPDATE, and DELETE statements.

Parameters:

  • content <String|Object> The data that is posted.

Returns: result Object

Examples:

put(content)

Performs an HTTP PUT, using the value of the content, to the URL endpoint. This object is useful with INSERT, UPDATE, and DELETE statements.

Parameters:

  • content <String | Object> The data that is used in a PUT request.

Returns: result Object

Examples:

query(key, value)

Adds a single query parameter.

Parameters:

  • key <String>
  • value <String>

Returns: request Object

Examples:

query(hashmap)

Adds all the query parameters based on key-name hashmap.

Parameters:

  • hashmap <Object>

Returns: request Object

Examples:

timeout(timeoutMillis)

Specifies the request timeout in milliseconds. This is useful when you want to cancel requests that take longer than expected.

Parameters:

  • timeoutMillis <Number> The number of seconds before your request times out.

Returns: N/A

Examples:

response Global Object

The response global object allows you to determine how responses are handled and is also used to set the value to the data you'd like to return, as an E4X object, a JSON structure, or simply a string.

Object Description
object Contains the results of your execute script. Set this value to the data you'd like to return, as an E4X object, a JSON structure, or simply a string.

result Object

The result object contains the results of your execute script.

The table below lists the properties of the result object.

Property Description Data Type
response Get the response from the remote service. If the response content type is not application/json or text/xml then YQL provides a string. If JSON or XML is specified, the E4X representation of the data is returned. E4X object or string
headers The headers returned from the response. object
status The HTTP status code. string
timeout Indicates if the call timed out. boolean
url The URL used to make the request. string

Global Variables

The following global variables are available for use within the execute element of YQL Open Data Tables:

Variable Description
input This global variable is available for each binding within the inputs element such as key, value, or map. For example, to call the first binding below you would use nameofid.

var mycontent = nameofid;

Important

If the id name uses an illegal identifier, such as the use of hyphens, you must instead use the inputs global variable.

When a map binding is present in the Open Data Table, the global variable is present as a named hashtable. Each value provided in the YQL statement is set in the hashmap.

inputs

This global variable is an array that contains each binding within the inputs element, along with its value. For example, to call the second binding above, you would use inputs[fieldname]:

var mycontent =inputs['field-name'];

Table of Contents