How to count words in a JSON String Element

Good Evening,

I need to count the words in a given JSON String:

“Text”:“This is a sentence”

I already searched around but didn t found anything I can use. Maybe somebody can point me in the right direction on how to do this in n8n.

Thanks
Bln

I played a little bit around with the code node and the following script

var wordCount = 0;
var key = "Text";

for (const item of items) {
  
  if (item.hasOwnProperty(key)) {
     var value = jsonObject[key];
        // Check if the value is a string
        if (typeof value === 'string') {
            // Split the string into an array of words
            var words = value.split(' ');
            // Add the number of words in the string to the word count
            wordCount += words.length;
        }
    }
  }

return [
  {
    json: {
      wordCount
    }
  }
]

But somehow it is not working well, I always get 0 as an answer.

The input to the code node are multiple Items containing the Key “Text” and then the text itself.

The most simple version would be the following expression:

{{ $json["Text"].split(' ').length }}
2 Likes

works perfectly, Thanks a lot jan!

1 Like

Glad to hear that it was helpful. Have fun!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.