The miva_json_decode(...) function in Mivascript is very easy to use. Better yet, it's wonderfully useful.
The miva json encode function is not built into Mivascript, however there is a json_encode(...) function in the Miva Merchant API that let's you use it in your modules or in template Store Morph Technology (SMT) code. We'll take a quick look at both of these and how they can be used in Miva Merchant templates.
Here is a block of basic json set up in SMT code. Using MvCAPTURE is the easiest way to put the JSON into a variable because there is no need to deal with any special formatting.
"idea":"Theory of Relativity"
"idea":"Everything Edison Took Credit For"
This JSON block is now stored in
l.settings:ads_json - note that in a module you would use the MvCAPTURE tag.
The reason to use
l.settings style variables in template coding (SMT) is that displaying the data is much easier.
&mvt:variable; is faster and cleaner looking than using
mvt:eval. Not everything is going to work with
l.settings so use it where you can.
Make an array out of
l.settings:ads_json by using the
miva_json_decode(...) function and display the data in a loop:
<mvt:assign name="l.json_convert_ok" value="miva_json_decode(l.settings:scientists,l.settings:json_array)" />
<mvt:if expr="l.json_convert_ok NE 1">
<p>JSON is invalid.</p>
<mvt:foreach iterator="scientist" array="json_array:scientists">
<b>Favorite Ice Cream:</b> &mvt:scientist:ice_cream;
<b>Popular idea:</b> &mvt:scientist:idea;
miva_json_decode(...) function returns a 1 if the JSON is decoded successfully. It's generally good to check for things like this so the code above includes an
mvt:if conditional to make sure the data is OK.
The output of the code above is:
Name: Albert Einstein
Favorite Ice Cream: Vanilla
Idea: Theory of Relativity
Name: Ernest Rutherford
Favorite Ice Cream: Pistacio
Idea: Everything Edison Took Credit For
Name: Stephen Hawkins
Favorite Ice Cream: none
Idea: Hawking radiation