How to read in data from a JSON file

This lesson will show you how to load a JSON file and convert the data into a LiveCode array, making it easy to use the data in your application.

JOSN files are a very useful for things like storing preference settings and sharing data with other programs.

You can find out more about JSON as www.json.org.

Create a stack with a button

Ensure you have a JSON file ready to load. In this example I have is a JSON file containing the capital cities of countries. It is a simple example but your JSON file can be as complex as you need.

Open the Script Editor for the button and add this mouseUp handler.

  • Ask the user to choose a file
  • Load in the data from the JSON file
  • Convert the JSON to a LiveCode array using the JSONToArray function.
on mouseUp pMouseButton
   local tFile, tData, tArray
   answer file "Choose a JSON file to load" with type "JSON|json|JSON"
   
   if the result is not "cancel" then
      put it into tFile
      put url ("file:" & tFile) into tData
      put JSONToArray(tData) into tArray
   end if
end mouseUp
Click to copy

Put a breakpoint on end if so we can check the array in the Variables pane of the Script Editor.

  • Ensure you are in Run mode
  • Click the "Load JSON" button
  • Select a JSON file
  • Check the Variables pane of the Script Editor to see the JSON data converted to a LiveCode array.

Converting an array to JSON

If you need to convert the contents of an array to JSON so you can save it out to file you can use the arrayToJSON function.

For example to save an array of preferences you might use

on savePreferences pPrefsArray
   local tPrefsFile, tJSONData
   
   put specialFolderPath("preferences") & "/myApp.json" into tPrefsFile
   put arrayToJSON(pPrefsArray,,true) into tJSONData
   put tJSONData into url ("file:" & tPrefsFile)
end savePreferences
Click to copy

This will store your preferences array as JSON, ready to be read in the next time the app is started.

{
  "displayMode": "Light",
  "name": "Elanor",
  "textSize": 14
}
Click to copy

0 Comments

Add your comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.