How can I count the number of JSON objects in a space separated string?

I have a list of json objects separated by spaces in a string

"{"case_id":"454450f6-02f0-4ae6-893b-18e7fb98b615","sample_barcode":"ID1"}  {"case_id":"454450f6-02f0-4ae6-893b-18e7fb98b616","sample_barcode":"ID2"}  {"case_id":"454450f6-02f0-4ae6-893b-18e7fb98b617","sample_barcode":"ID3"}"

how can I count how many objects i have in the string

If there are no spaces anywhere in the json objects and only between them (as in your example), you should be able to use thecount-selected function:

https://confluence.dimagi.com/display/commcarepublic/CommCare+Functions#CommCareFunctions-count-selected

If there may be spaces inside the object, this won't work as expected, and you might have to do something more complicated (like using replace to collapse each object into something more easily counted).

Thanks @Ethan_Soergel has worked. I thought count selected was only for checkbox questions. This has simplified things

it works for ANY space separated list.

I've used "Selected-at" in order to figure out things like ratings, steps in a workflow, etc...

So maybe like a text string that has something like "First Second Third Fourth DNA DNA DNA DNA DNA"
where selected-at can return one value depending on a counter, or a repeat group position

is there any work around for selected-at for strings with spaces that are space separated

e.g

selected-at(" 'First Name 1' 'First Name 2' ", 2) 
producing
First Name 2 

replace spaces with _ using translate function
do the selected-at call
replace _ with spaces

let me rephrase,

when you compose first name 1, compose it as first_name_1
use the join to get a space separated list
do the selected at to get first_name_X
replace _ with spaces to get first name x

1 Like

ah yes this will work. Thanks.

1 Like