Make a JSON Configuration file in Miva Script

Miva Merchant Modules and Development
The Miva Scripting language has a fantastic JSON parser that makes it easy to use JSON files for configurations and other plain text settings.

Make a JSON Configuration file in Miva Script

Use Miva Script to create a simple configuration file using JSON format.


The Miva Scripting language has a fantastic JSON parser that makes it easy to use JSON files for configurations and other plain text settings.

by Scot Ranney • June 18, 2019

Miva Scripting 101


JSON is a very nice way to store data in plain text format. This is useful because you can edit it in a text area in your web app or Miva Merchant module, or simply edit it in a text editor.

Let's say your json file is called config.json and you want load the settings you've saved in it. 

Let's say this is what the json file looks like:

{
    "name":"Scot Ranney",
    "website_name":"Scot's Scripts",
    "city":"Bellingham",
    "state":"Washington"
}

The code below reads that file and puts the data into a structure you can use in your Miva script. This example assumes the json file is in the same directory as the script or module.

<mvif expr="{ sexists('config.json') }">
    <mvassign name="l.ok" value="{ file_read('config.json','script',l.json) }" />
    <mvassign name="l.ok" value="{ miva_json_decode(l.json,l.config) }" />
</mvif>

1. Use the built in Mivascript function sexists(...)  to see if the file exists. This way we don't get any error messages if the file isn't there.

2. Use the built in Mivascript function file_read(...) to load the data into a variable. In this case I decided to use l.json to hold the data from the json file.

3. Use the built in Mivascript function miva_json_decode(...)  to convert the json data into a structure. In this case the data would be available like this:

l.config:name
l.config:website_name
l.config:city
l.config:state

You could display it in any way, such as a welcome message:

Hello <MvEVAL EXPR= "{ l.config:name }">, how is the weather in <MvEVAL EXPR= "{ l.config:city $ ', ' $ l.config:state }">?

This would display as:

Hello Scot, how is the weather in Bellingham, Washington?

overall rating:
my rating: log in to rate

html mivascript tutorial

The blog posts on Scot's Scripts are made using by Scot's Blogger, a full featured Wordpress replacement Miva Merchant blogging module.