Save the JSON response from JavaScript to a different file extension in a visually appealing layout

I've created a script to generate both the CSR and private key.

The response displayed in the <textarea> is well-formatted with newline characters (assuming familiarity with the correct CSR/Private key format).

However, I'm encountering an issue when saving the private key as a .pfx file, resulting in poor formatting.

Below is how it appears in the browser within a <textarea>:

-----BEGIN PRIVATE KEY-----
MIIEowIBAAKCAQEAsUM5i1BX1NWS1CGsou86LN3oRcfkA63FdqneDLi36602dxQO
pSPabp8lqR+LgIWq/nIxShbZgc5YwlmhylrqYm1jdHXUQlNhBjsJE6Y0SwybXD9k
ERyWgFfaFLeUjUTXax01/M9oh4JQ+o4pWz+cw3oUjklH5iviLx34bZMq0k5azLus
312FRgA1x2AKG4QWUwTijTISYZ4mtLDTli2iqWVvPpLi87hLKTAMmLdJZ8hJkXOJ
QYRALpiERwX4lhckh1xnr/NfzE+QY0zxGwmvE4Uk0MqT7liUfqPnXiMLIIGuC/pt
xf2SXQBv/A9eus2jI0gM627iyvbDdkw0E1B+5QIDAQABAoIBAQCjpZM/aSnc5FsM
GhZ9yWsktqzTlymKt+dfmIzVo8av/hYVMuAeVw42KBilnOi1+zEUfKnCY3vkGXLZ
4dO6s9pEigZSIuGVZdJh5SiJClymmHnpXOBt572NuQ0tKRosnUxep/YKchRnXciS
t6G4iu6XjGHjxgVpmkPTCdEqn73drkf4jeQQrXWJQeOFH3b0e7XwvkoBKrjn6Tu3
uUUR...

This is how it looks after being saved as a file:

"-----BEGIN PRIVATE KEY-----\nMIIEowIBAAKCAQEAsUM5i1BX1NWS1CGsou86LN3oRcfkA63FdqneDLi36602dxQO\npSPabp8lqR+LgIWq/nIxShbZgc5YwlmhylrqYm1jdHXUQlNhBjsJE6Y0SwybXD9k\nERyWgFfaFLeUjUTXax01/M9oh4JQ+o4pWz+cw3oUjklH5iviLx34bZMq0k5azLus\n312FRgA1x2AKG4QWUwTijTISYZ4mtLDTli2iqWVvPpLi87hLKTAMmLdJZ8hJkXOJ\nQYRALpiERwX4lhckh1xnr/NfzE+QY0zxGwmvE4Uk0MqT7liUfqPnXiMLIIGuC/pt\nxf2SXQBv/A9eus2jI0gM62...

Here's the code used for generating the CSR:

var csrResult = (JSON.parse(csr))
var csrResultResdata = JSON.parse(csrResult["resdata"]["csrgen"]["context"])
var csrResultResdataCSR = csrResultResdata["csr"]
var csrSpliter = csrResultResdataCSR.split("\n\n")
var csrOnly = csrSpliter[0]
var privateKeyOnly = csrSpliter[1]
var exportName = "private_key"
downloadObjectAsJson(privateKeyOnly, exportName)

And the code to save it as a file:

function downloadObjectAsJson(exportObj, exportName){
    var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
    var downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href",     dataStr);
    downloadAnchorNode.setAttribute("download", exportName + ".pfx");
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
}

I would appreciate assistance in improving the file content layout.

Lastly, here is the original API response:

{
    "result": {
        "code": "0",
        "msg": "Command completed successfully"
    },
    "resdata": {
        "csrgen": {
            "context": "{\"csr\":\"-----BEGIN NEW CERTIFICATE REQUEST-----\\nMIICtjCCAZ4CAQAwcTELMAkGA1UEBhMCTVkxETAPBgNVBAgTCFNlbGFuZ29yMRUw\\nEwYDVQQHEwxQdWNob25nIEpheWExDzANBgNVBAoMBuerpeWNqzEPMA0GA1UECwwG\\n56ul5Y2rMRYwFAYDVQQDEw1hYmMudGt0YW4uY29tMIIBIjANBgkqhkiG9w0BAQEF\\nAAOCAQ8AMIIBCgKCAQEAj3SON7mz0TZwFHAfy/m3vKICH2BjaZdWJWi7ZPLo2uYC\\n6070cU7hd5iM8+q7VEYSUJb8XisuGpKSakx0xWXuXkJfrciR9P5dypEWAUle3e+z\\nHaQMhu9eJu7W0do96f8WLJoy/T1jYIF6p2hhwRy368FrUtWGJQ+6SH5MTTRytOl5\\nayPdvJiW2AmTwv26OG47eDXZqQOFO+MBKd12DYZxBDTpswubhs1rYT5tA5yQA6HP\\ndG+40LxoNqcZVJ/aYvftOVS3JS...

Answer №1

Is there a reason for storing your PFX file in JSON format? You can simply remove the JSON.stringify and output it as plain text since you are passing in a basic string anyway. Using stringify only adds quote marks and encodes newlines unnecessarily.

var dataStr = "data:text/plain;charset=utf-8," + exportObj;

https://i.sstatic.net/TnTfO.png

Check out this JSbin link to see it working correctly: http://jsbin.com/lipaxuhidi/edit?html,js,output

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does starting up the Firebase emulators trigger the execution of one of my functions as well?

Upon running firebase emulators:start --only functions,firestore, the output I receive is as follows: $ firebase emulators:start --only functions,firestore i emulators: Starting emulators: functions, firestore ⚠ functions: The following emulators are ...

What do I need to add to my code in order to receive a JSON response from the URL I am

I developed a custom Python client REST API wrap for an authenticated Okta pricing API. Although my code is functional, I am not receiving any response. My goal is to retrieve a JSON response, and I have considered using a print statement, but I am unsur ...

processing an array using ajax form submission

Trying to manage an array that is returned from a PHP file after submitting form data. The value of the data after form submission is = ARRAY but I am unable to use this array in any way. Any suggestions on how to handle this array? Javascript: $(&apo ...

Targeting props within a Class Component: A Step-by-Step Guide

I am currently working on a MultiStep Form project. On the final page of the form, my goal is to push all the collected data to Firebase. I have been utilizing props and states to pass values from one page to another. However, I'm facing an issue in t ...

Decode Jackson - a process to extract and translate multiple base enums from

Can enums with a one-based index be deserialized successfully? enum Status { Active, Inactive } The value {status:1} should correspond to Status.Active, but Jackson is incorrectly mapping it to Status.Inactive. ...

Is there a way to eliminate nested or parent objects from an array using JavaScript?

I am looking for a way to remove an object based on its id without using a MongoDB query. Instead, I want to remove the object from an array stored in a variable using a JavaScript function. For example, if I provide id=ObjectId("5b693e7ddd65ec16a46b7f82" ...

Unique title: "Curved Blocks with Unusual Shapes in SVG Path

Hey there, I'm new to working with SVG and Highcharts. I found a jsfiddle online that I would like to customize for my project, but I've encountered an issue with the rounded corner blocks of lines in the Result panel. Here is the link to the js ...

What sets onEnter apart from onStart in ui-router?

I am transitioning to the latest version of ui-router (1.0.0-alpha.5) and I am exploring how to utilize the onEnter hook versus the onStart hook: $transitions.onStart() as well as $transitions.onEnter() In previous versions, we only had the event $sta ...

Having trouble getting Typescript code to function properly when using commonjs style require statements

I am completely new to Typescript, Node.js, and Express. Following the instructions outlined in this tutorial (https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript), I set up my project exactly as described there. The ...

Show side by side using javascript

My dilemma lies in having a set of cards that are meant to be displayed inline, but I have to initially hide them using "display: none". When a specific button is clicked, I aim to reveal these cards; however, upon doing so, each card seems to occupy its o ...

Opacity effect on input text when it exceeds the input boundaries

I'm having an issue: I need to create inputs with different states, including when the text is longer than the input itself. In this case, the extra text should fade out with a gradient transparency effect: https://i.sstatic.net/r5qQu.jpg Here is my ...

How to automatically redirect empty routes to a specific route in Next.js

When visiting a non-existent endpoint in Next.js, I receive a 404 error. What I actually want is for all unused routes to automatically redirect to a default route; specifically, the landing page. I've spent more than an hour trying to figure this ou ...

Utilizing a TypeScript definition file (.d.ts) for typings in JavaScript code does not provide alerts for errors regarding primitive types

In my JavaScript component, I have a simple exporting statement: ./component/index.js : export const t = 'string value'; This component also has a TypeScript definition file: ./component/index.d.ts : export const t: number; A very basic Typ ...

Utilizing JSON format for submitting dynamic form data

When using AJAX post, I have successfully passed predefined data like this: //var data = {"name": "Testing", "email": "[email protected]", "cpf": "9876543210"}; However, I am facing difficulty in dynamically passing the form data. I would appreciat ...

Highlighting the home page in the navigation menu even when on a subroute such as blog/post in the next.js framework

After creating a navigation component in Next JS and framer-motion to emphasize the current page, I encountered an issue. The problem arises when navigating to a sub route like 'localhost:3000/blog/post', where the home tab remains highlighted i ...

struggling to properly interpret daylife JSON data using jQuery

Is there a way to use $.getJSON to access the "name", "url", "headline", "timestamp", and "excerpt" from the array "article"? Link to API endpoint ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

Error encountered when deploying the app to the live server: 500 Internal Server Issue

I am encountering an issue with my ASP.Net web app's ajax file upload feature. While it works perfectly on my local host machine during testing, I face a 500 Internal Server error when I try to publish it to a website. The console output in Google Chr ...

What is the proper way to retrieve multiple property values stored in a property name using getJSON

I'm having trouble getting multiple languages to work in my code. Could someone assist me and provide guidance on how to write multiple choices for the property name language? When I input code like this to display only Dota 2 games in English, every ...

Is it possible to utilize the output of a function nested within a method in a different method?

I am currently facing a challenge with my constructor function. It is supposed to return several methods, but I'm having trouble using the value from this section of code: var info = JSON.parse(xhr.responseText); Specifically, I can't figure ou ...