0

My app makes another software for its purpose and has a dynamic json file that needs to be presented to the user to copy and paste.

I have the json file, and the code, and the user needs to be able to copy that json file exactly as it is.

When I try to include the large json file in my JSX, the syntax goes crazy and throws errors.

What do I need to include in my JSX so that it can display my json data exactly as the json data is written.

Or, how would I set a var myFile = myFile.json and then display that file in my component so that the user can copy and paste it?

Zach
  • 468
  • 9
  • 17
  • 1
    so output it to a textarea so they can copy it? – epascarello Jul 02 '18 at 17:22
  • You're really asking 2 things: 1) How do I get the contents of a Json file, and 2) How do I display those contents pretty. See [here](https://stackoverflow.com/questions/31758081/loading-json-data-from-local-file-into-react-js) for an answer to the first and below for answers to the second. – SamVK Jul 02 '18 at 17:41

2 Answers2

2

JSON.stringify() has a built-in pretty-print option. Pass 4 as the third argument (or your indent spacing of choice) for pretty output. Then, throw that output into a <pre> tag (or any tag with white-space: pre CSS styling added to preserve indents.)

e.g.

const exampleJson = { "name": "John", "age": 30, "car": null };

const prettyJson = JSON.stringify(exampleJson, null, 4); // indent 4 spaces

document.getElementById('json').textContent = prettyJson;

// EDIT: or just `return <pre>{prettyJson}</pre>` in jsx.
<body>
  <pre id='json'></pre>
</body>

As for the copying, you could just let the user highlight and copy, or take a look document.execCommand("copy") to add a user-friendly button.

SamVK
  • 3,077
  • 1
  • 14
  • 19
0

You can do something like this in the render method of your component:

var prettifyJson = JSON.stringify(myFile, null, 4);

<pre>{ prettifyJson }</pre>
deowk
  • 4,280
  • 1
  • 25
  • 34