Using data in JSON format in Snack


There are lots of ways to use data with apps made with Snack Expo. Sometimes the data is stored as JSON, that mean JavaScript Object Notation. In this format, the data can be stored easily as Key-Value pairs and can also be converted to a CSV file. In this article, using javascript on Snack, the methods to use JSON data are specified. In example 1, the method to read this data and to display it as a table is given. In the second example, the methods of saving the JSON data as a CSV file and to download it, is shown.

Algorithm-1

Step 1 − Import View from 'react-native'. Also import JSON data from the json file. Here, for example products.json is used

Step 2 − Make the App.js and write the code.

Step 3 − Use id as the key and fetch all products from the json file.

Step 4 − First show the header and then use map function to fetch each product item. Select the columns to display.

Step 5 − Show the data in form of table using <table>, <thead>, <tr> and <th> tags.

Step 6 − Check the result.

JSON file used in examples : filename – products.json

Example

{
   "products": [
      {
         "id": 68,
         "title": "School shoes",
         "price": 122,
         "quantity": 3,
         "total": 160,
         "discount%": 50,
         "discountedRate": 80
      },
      {
         "id": 82,
         "title": "Washing Gloves",
         "price": 50,
         "quantity": 2,
         "total": 60,
         "discount%": 10,
         "discountedRate": 45
      },
      {
         "id": 28,
         "title": "Moisturizer 100ml",
         "price": 45,
         "quantity": 2,
         "total": 90,
         "discount%": 13.1,
         "discountedRate": 70
      },
      {
         "id": 92,
         "title": "Leather Belt",
         "price": 900,
         "quantity": 1,
         "total": 950,
         "discount%": 19.77,
         "discountedRate": 766
      },
      {
         "id": 49,
         "title": "Woollen Shawl",
         "price": 800,
         "quantity": 2,
         "total": 1300,
         "discount%": 20,
         "discountedRate": 994
      }
   ]
}

Example 1: Reading JSON data and showing it as a table.

The important file used in the project is

  • App.js

App.js : This is the main javascript file for this project.

Example

import productData from './products.json'

import {Component} from "react";
import {View} from "react-native";

export default class JSONEXAMPLE extends Component {
   render(){
      return (
         <View style={{padding: 10}}>
         <h2>Products Ordered</h2>

         <table>
            <thead>
               <tr>
                  <th>ID</th>
                  <th>Title</th>
                  <th>Price</th>
                  <th>Quantity</th>
               </tr>
            </thead>
            <tbody>
               {productData.products.map(products => {
               const { id, title, price, quantity } = products
               return (
               <tr key={id}>
                  <td>{id}</td>
                  <td>{title}</td>
                  <td>{price}</td>
                  <td>{quantity}</td>
               </tr>
               )
               })}
            </tbody>
         </table>
         </View>
      )
   }
}

Viewing The Result

The result can be seen online. As the user types in the code, the Web view is selected by default and the result appears instantly.

JSON data showing as a table in the Web view in Snack

Algorithm-2

Step 1 − Import View from 'react-native'. Also import JSON data from the json file. Here, for example products.json is used

Step 2 − Make the App.js and write the code.

Step 3 − Use id as the key and fetch all products from the json file and display the products info in a table form.

Step 4 − Write a function downldFl() with parameters data, filename and filetype. Use Blob() to specify the file type and use window.URL.createObjectURL(blob) to download the file.

Step 5 − Join the header with ‘,’ and then join the json content separated by “
” .

Step 6 − Click the download CSV and check the downloaded file with the result.

Example 2: Converting JSON data to CSV and downloading the file.

The Important file used in the project is

  • App.js

App.js : This is the main javascript file for this project.

Example

import productData from './products.json'
import {View} from "react-native";

const downldFl = ({ data, fl_name, fl_type }) => {
   const blobb = new Blob([data], { type: fl_type })
   const lnk = document.createElement('a');
   lnk.download = fl_name;
   lnk.href = window.URL.createObjectURL(blobb);
   lnk.click();
   URL.revokeObjectURL(lnk.href);
   lnk.remove();
}

const downloadCSVfile = e => {
   e.preventDefault()

   let headers = ['Id,Title,Price,Quantity']

   let productsCsv = productData.products.reduce((str1, product) => {
   const { id, title, price, quantity } = product
   str1.push([id,title, price, quantity].join(','))
   return str1
   }, [])

   downldFl({
         data: [...headers, ...productsCsv].join('
'), fl_name: 'products.csv', fl_type: 'text/csv', } ) } export default function JSONEXAMPLETWO() { return ( <View style={{padding: 10}}> <h2> Download JSON as CSV</h2> <table className='productsTable'> <thead> <tr> <th>ID</th> <th>Title</th> <th>Price</th> <th>Quantity</th> </tr> </thead> <tbody> {productData.products.map(products => { const { id, title, price, quantity } = products return ( <tr key={id}> <td>{id}</td> <td>{title}</td> <td>{price}</td> <td>{quantity}</td> </tr> ) } ) } </tbody> </table> <button type='button' onClick={downloadCSVfile}> Download CSV </button> </View> ) }

Viewing The Result

The result can be seen online. As the user clicks the download button, the file is downloaded and the result appears instantly.

Pressing the download CSV button gets the file downloaded.

Showing the contents of the downloaded CSV file made from JSON.

In this article, using two different examples, the methods of using JSON in Expo Snack apps are given. First the method is given for reading a json file and showing its content in a table form. Then the method to save the selected JSON data in CSV format and then downloading that file is given.

Updated on: 02-May-2023

498 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements