0

Have a JSON object that I'm trying to pass to my Javascript through a script tag in my markup like so:

<script type="text/json" id="json-data">
{
  "terms": "{{ entry.termsAgreement }}",
  "sectionHeader": {{ entry.formSection }}
}

However, I'm getting an error that says:

Object of class Craft\ElementCriteriaModel could not be converted to string.

formSection is a Matrix field. How can I pass this along to have access to it in Javascript? I tried

JSON.stringify({{ entry.formSection }})

but no luck.

Thanks.

1
  • 1
    If the JSON can come from an external request, you might consider using the Element API from P&T. Either way, you're probably going to want to be more explicit about looping through and outputting what you need from the Matrix fields. You may be able to easily convert the model to JSON somehow, but I expect you'll end up with tons of extra information that'll just add cruft to your page.
    – Matt Stein
    Mar 9 '16 at 19:56
1

I'd strongly recommend looking at the Element API plugin for this.

If you're dead set against that, there are other examples of how to pull out section data in Craft for rolling your own JSON.

For Matrix it'd be no different that if your were pulling Matrix data out to be output in HTML instead of JSON (looping through blocks, grabbing fields, etc). Lots of examples in the Matrix templating docs.

The error you're getting is because when you simply output entry.myMatrixHandle, you're technically given back an ElementCriteriaModel object and the Element API plugin tries to convert that to a string to display in the JSON data and it doesn't know how to convert that object to a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.