Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Display Key and Value Pairs from JSON in ReactJS

Want to learn how to display key and value pairs from JSON in ReactJS? Check out this guide for a thorough, but succinct explanation of how to do just that!

Jan 26, 2020 • 10 Minute Read

Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy to read and write and for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition.

JSON is basically a collection of name/value pairs, where the name will always be a string and values can be a string (in double quotes), a number, a boolean (true or false), null, an object, or an array. Each name-value pair will be separated by a comma. JSON is a text format that is completely language independent, and it is an ideal way of exchanging data.

Before jumping in, let's discuss React, a popular JavaScript library for building user interfaces. It basically handles the view-layer of the application. The best part is that it allows you to break a component into smaller, reusable components. Instead of putting all the logic into a single file, writing smaller components gives us a better edge. By writing well-encapsulated components, we are essentially making a testable app with a good separation of concerns and maximum code reuse.

Rules on Name Strings

JSON syntax does not impose any restrictions on the strings used as name, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs. These are all semantic considerations that may be defined by JSON processors or in specifications defining specific uses of JSON for data interchange.

Possible Values of Name

A JSON value can be an object, array, number, string, true, false, or null, and JSON structure can be nested up to any level. So for the sake of simplicity and to understand the rendering part easily, let's assume a JSON name can have two types of values, a leaf value or a nested structure. A leaf value can be string, number, true, false, or null. For a nested structure, value will be an array (ordered list) or an object (unordered set of name-value pairs).

Objects and arrays are useful for representing and sharing complex nested data.

Example:

      {
  "string": "Pluralsight",
  "number": 1,
  "true": true,
  "false": false,
  "null": null,
  "arrayOfStrings": ["a", "b", "c", "d"],
  "arrayOfNumbers": [1, 2, 3, 4, 5],
  "arrayOfBooleans": [true, false, true, false],
  "arrayOfObjects": [{ "a": 1 }, { "a": 2}],
  "object": {
    "anyKey": "anyValue"
  }
}
    

How to Render Dynamic Value in JSX

Before beginning the discussion on rendering name-value pair, lets cover the rendering of dynamic values in React and what exactly JSX is.

We do not necessarily use JSX with React, but it is very helpful when working with UI. With React, we don't write HTML for UI creation, we write JSX. JSX is basically syntax extension to JavaScript. Nothing but syntactic sugar for React.createElement(component, props, ...children).

For example, these two lines are same. The second line is transpiled version of the first.

      <div>Hello World!!!</div> // jsx
React.createElement('div', null, 'Hello World!!!');
    

To render dynamic values in JSX, we use {} (curly braces). Code that we put in {} will be treated as JS expression and will be evaluated at runtime (the expression must be a valid JS expression).

Rendering JSON Values

There can be many sources of JSON files, either through an API call or importing a locally created JSON file (with extension .json). In most front-end applications, we interact with a server to fetch the data and fill the UI skeleton or template. For now, I am assuming JSON is available in component. One by one, we will discuss all the values and how to render or show them in UI.

Rendering String/Number Values

A string is a sequence of zero or more Unicode characters wrapped in double quotes. String or number values can be rendered directly in JSX using {}. For example:

      import React from 'react';

const sampleJSON = {
  "string": "PluralSight",
  "number": 1
};

function App() {
  return(
    <div>
      <p>String : {sampleJSON.string}</p>
      <p>Number : {sampleJSON.number}</p>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('app'));
    

Rendering Null/True/False

Boolean values (true and false), null, and undefined are valid children, but these values will not be rendered in UI if you put them directly inside {} in JSX. For example, all these JSX expressions will result in the same empty div:

      <div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>
<div>{true}</div>
    

If you want a value like false, true, null, or undefined to show in the output, you have to convert it to a string first.

For example:

      <div>{String(true)}</div>
<div>{String(false)}</div>
<div>{String(undefined)}</div>
<div>{String(null)}</div>
    

In the output, this will render true, false, undefined, and null respectively.

Note: There are many possible ways to convert these values into a string. Use any one.

Rendering Objects

Here comes the most tricky part of the JSON name-value pair rendering. React does not directly allow us to render any object in JSX. If we mistakenly do that, it will result in the following error:

Objects are not valid as a React child (found: object with keys { a, b, c }). If you meant to render a collection of children, use an array instead.

Now the question is how to render an object without breaking the code?

As we have already discussed, we can only render leaf values. In the case of an object, we have to specify the exact property name using either dot notation or bracket notation, which has the renderable value.

For example, to render all the properties of the object in the UI, we need to run a loop:

      import React from 'react';
import ReactDOM from 'react-dom';

const sampleJSON = {
  "object": {
    "name": "Pluralsight",
    "number": 1,
    "address": "India",
    "website": "https://www.pluralsight.com/"
  }
}

function App() {

  return (
    <div>
      {
        Object.keys(sampleJSON.object).map((key, i) => (
          <p key={i}>
            <span>Key Name: {key}</span>
            <span>Value: {sampleJSON.object[key]}</span>
          </p>
        )
      }
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('app'));
    

Note: If we want to show only one renderable property in UI, then we don't need to run a loop. We can simply write it using dot notation. For example, to display the name value of the object:

      <p>Name: {sampleJSON.object.name}</p>
    

Rendering Array Values

And now, the last part of the guide, but of course not the least. Rendering array values in UI with proper styling is one of the common things we do in applications such as Todo App, Travel App, etc.

First let's discuss a case where we want to render an array of leaf values without any extra styling or HTML tag for each item. This will be similar to joining the values using a comma or space, then rendering that string. Array (with all renderable value) can be rendered directly like this:

      import React from 'react';
import ReactDOM from 'react-dom';

const sampleJSON = {
  "arrOfNumbers": [1, 2, 3, 4],
  "arrOfStrings": ["a", "b", "c", "d"]
}

function App() {
  return (
    <div>
      {sampleJSON.arrOfNumbers}
      {sampleJSON.arrOfStrings}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('app'));
    

Next, either we want separate styling for each item or the item is not a directly renderable value. In all those cases, we need to run a loop. Luckily, this is easy to do in JSX using Array.map. When we use map, it will run through all the items in that array and we can return a new array of JSX.

Consider this example:

      import React from 'react';
import ReactDOM from 'react-dom';

const sampleJSON = {
  "arrOfNumbers": [1, 2, 3, 4],
  "arrOfStrings": ["a", "b", "c", "d"],
  "arrOfObjects": [{ "a": 1, "b": 1 }, { "a": 2, "b": 2 }, { "a": 3, "b": 3 }]
}

function App() {
  return (
    <div>

      <h2>Array of Numbers:</h2>
      <ul>
        {sampleJSON.arrOfNumbers.map((item, i) => {
          return <li key={i}>{item}</li>
        })}
      </ul>

      <h2>Array of Strings:</h2>
      <ul>
        {sampleJSON.arrOfStrings.map((item, i) => {
          return <li key={i}>{item}</li>
        })}
      </ul>

      <h2>Array of Objects:</h2>
      <ul>
        {sampleJSON.arrOfObjects.map((item, i) => {
          return <li key={i}>{item.a} - {item.b}</li>
        })}
      </ul>

    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('app'));
    

Conclusion

I hope this guide was helpful in understanding the basics of JSON, React, JSX, and how to render different types of values efficiently to create meaningful user interfaces.

Learn More

Explore these JSON and React courses from Pluralsight to continue learning: