3

I am trying to get one object returned from a list of objects;

list = [{"name":"Joe","id":1},{"name":"Fred","id":2}]

I want to output the object exactly like the format below;

{"name":"Joe","id":1}

It throws errors when I want to access the object in its entirety;

${list?first} -> Error: Expected a string or something automatically...

Testing this on https://try.freemarker.apache.org/ but I can't seem to be able to extract the full first object, whilst accessing a property from that object works fine..?

I understand that this is somewhat of an odd use case to display the object like that. I need it for a business program that uses freemarker and I want to assign the object back into a variable, which accepts this format.

1 Answer 1

2

You can show values that can be converted to String as error (below) suggest

<#assign item = list[0]>
${item.name} ${item.id} 
For "${...}" content: Expected a string or something automatically convertible to 
string (number, date or boolean), or "template output" , but this has evaluated to a 
sequence (ArrayList wrapped into f.t.DefaultListAdapter):
==> list  [in nameless template at line 1, column 3]

You can check freemarker parse a JSON answers, for executing similar as:

<#assign array = '[{"name":"Joe","id":1},{"name":"Fred","id":2}]'> 
<#assign object = array?eval[0]> 
<#list object?keys as key>"${key}":"${object[key]}"
</#list>
Sign up to request clarification or add additional context in comments.

5 Comments

I can do the same with ${list?first.name}, but how to retrieve the full object like {"name":"Joe","id":1} ? The object properties are not always the same, so I just want to have the full object.
@Bastiaan you get it in first line <#assign item = list[0]>
I understand that items contains the first object. However I still cannot output exactly {"name":"Joe","id":1} in any way? When I do the assign and then after that ${item} I get the exact same error. Have elaborated a bit more in the question to explain the use case
Thanks! I have it working, do you want to update your answer with this, so I can accept it as the answer? <#assign array = '[{"name":"Joe","id":1},{"name":"Fred","id":2}]'> <#assign object = array?eval[0]> <#list object?keys as key>"${key}":"${object[key]}"</#list>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.