Using SSJS to List Metadata Values

(Nick Papadatos) #1

Matrix Version: 5.5

Hello, can anyone help me here as I’m a tad confused as to why I’m getting a value of 1 when there’s no metadata.

example metadata code values: XYZ-1234, ABC-567 etc
runat server:
let array2 = %asset_metadata_myMetadata^explode:, %

If there’s no metadata added to the page I still get “1” printed - if I have one metadata value I still get “1”.
Should it be 0 for empty and 1 if there’s a value ie; true/false?

Basically what I’m trying to acheive is if there’s metadata and array2 is greater than 0 then print codeTemplate else don’t.

     const codeTemplate =`
        <div class="pc-container">
         <h3>Research codes</h3> 
          <ul class="research-code-container">
 if(array2.length > 0) {           

What am I missing??

(David Schoen) #2

It’s because the underlying PHP explode will always return an array with something in it e.g:

echo json_encode([
    '' => explode(", ", ""),
    'foo' => explode(", ", "foo"),
    'foo, bar' => explode(", ", "foo, bar"),


    "": [
    "foo": [
    "foo, bar": [

You’re probably better off passing in the string and using JS to .split() it.

(Nick Papadatos) #3

Thanks David,
I just noticed when array2 is empty I get [""] instead of [] which gave me the value of 1.
Is there no keyword to fix this?

Update: I ended up just appending …^replace:"":% which now gave me a zero!
let array2 = %asset_metadata_myMetadata^explode:, ^replace:"":%;

I get array2 = [];
Happy dayz :slight_smile:

(David Schoen) #4

You would have to do something with a conditional i.e if empty, don’t convert to array. Which is just easier done in JS in my opinion.

<script runat="server">
    let myMetadata = "%asset_metadata_myMetadata^as_json%";
    let array2 = myMetadata.length ? myMetadata.split(", ") : [];

(David Schoen) #5

This’ll replace any empty strings in the final array as it’s operating over the raw string e.g it’d drop the empty element out of:

foo, , bar

This may be what you want, but it’s a little less intuitive than using something more explicit like .filter((i) => (i != '')).

(Nick Papadatos) #6

Really nice solutions David thank you.