Interviewer: Ameya Naik.

Build a JSONViewer tool that

  1. renders JSON in pretty way with 2 space padding for indentation
  2. supports collapse/expand functionality per node for navigation

For example, check out https://jsoneditoronline.org/

import React, { FC } from 'react'
import './App.css'
 
// Test JSON from https://fakestoreapi.com/users?limit=1
const USER_1_JSON_STRING: string = '{"address":{"geolocation":{"lat":"-37.3159","long":"81.1496"},"city":"kilcoole","street":"new road","number":7682,"zipcode":"12926-3874"},"id":1,"email":"john@gmail.com","username":"johnd","password":"m38rmF$","name":{"firstname":"john","lastname":"doe"},"phone":"1-570-236-7033"}';
 
// const USER_2_JSON_STRING: string = 
  // `[${USER_1_JSON_STRING}]`;
 
const USER_2_JSON_STRING: string = '[1,2,3]';
 
console.log('USER_2_JSON_STRING', USER_2_JSON_STRING);
 
const Node: FC<{
  jsonKey: string, value: any, isLast: boolean
}> = ({
  jsonKey, value, isLast,
}) => (
  <details>
    <summary>
      {`"${jsonKey}": `}
    </summary>
    <Renderer json={value}/>
    {/* {Array.isArray(value) ? ']' : '}'} */}
    {isLast ? '' :','}
  </details>
)
 
const Leaf: FC<{ jsonKey: string, value: any, isLast: boolean }> = ({
  jsonKey, value, isLast,
}) => (
  <div key={jsonKey}>
    {`"${jsonKey}": "${value.toString()}"${isLast ? '' :','}`}
  </div>
)
 
const Renderer: FC<{ json: any }> = ({ json }) => {
  const keys = Object.keys(json)
 
  const isArray = Array.isArray(json)
 
  return (
    <div>{isArray ? '[' : '{'}
      <div style={{ marginLeft: '20px' }}>
        {keys.map((key, i) => {
          const value = json[key]
          if (typeof value === 'object') {
            return <Node jsonKey={key} value={value} isLast={keys.length - 1 === i}/>
          }
          return <Leaf jsonKey={key} value={value} isLast={keys.length - 1 === i}/>
        })}
      </div>
      {isArray ? ']' : '}'}
    </div>
  )
}
 
export default function App() {
  const json = JSON.parse(USER_1_JSON_STRING)
  console.log(JSON.stringify(USER_1_JSON_STRING, null, 2))
  return (
    <div className="app">
      <div className="header">
          <span>JSON Viewer</span>          
      </div>
 
      <div className='content'>
          <Renderer json={JSON.parse(USER_1_JSON_STRING)}/>
          <hr/>
          <Renderer json={JSON.parse(USER_2_JSON_STRING)}/>
      </div>
    </div>
  )
}