Making adjustments to a JSON object before saving it to a file with Postman and Express

I have successfully created a POSTMAN call to a server that provides a JSON response containing a list of items as shown below:-

{
    "count": 6909,
    "setIds": [
        "1/7842/0889#001",
        "2/4259/0166#001",
        "ENT0730/0009",
        "9D/11181#002",
        "1/9676/0001#001",
        "2/4718/0001#004",
        "2/1783/0044#001",
        "1/4501/0001#001",
        "1/2028/0002#002",
        "2/3120/0079#001",
        "2/1672/0024#001",
        "2/3398/0064#001"
}

My objective now is to make subsequent calls to another server using the setID values and iterate through each item to cross-verify the responses. However, the challenge I encounter is that the second server requires the set id format with forward slashes converted to underscores and hashes to dots, such as:

"1/7842/0889#001"

should transform into

"1_7842_0889.001"

I have implemented code in POSTMAN to perform this conversion:

   var jsonData = pm.response.json()

    for (var i=0; i<jsonData.setIds.length; i++)
    {
    var new_j = jsonData.setIds[i].replace (/#/g, ".");
    var new_i = new_j.replace (/\//g, "_");
    }
})

While this code executes correctly line by line generating the desired output in the POSTMAN console, my main goal is to save the entire JSON data in the appropriate format to a file and then retrieve it line by line with modified data. Unfortunately, I am facing difficulties saving the data in the required form using my existing approach, indicating a probable oversight on my part. Is there a method to write content to a file incrementally within POSTMAN or via a scripted solution while manipulating the data during creation?

An alternative strategy could involve reading from the saved JSON response directly, processing the information using a pre-request script.

In an attempt to resolve this issue, I experimented with environmental variables. For example, in the initial call, I employed the following script:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable('setIds', JSON.stringify(jsonData));

Subsequently, my intention was to utilize this environment variable in a pre-request script for the second call to the express server where the payload is forwarded. Regrettably, this approach failed due to syntax errors, specifically encountering SyntaxError: Unexpected token {.

While exploring potential solutions, one possibility involves handling these procedures outside of POSTMAN using JavaScript. However, I feel slightly overwhelmed by the starting point. Any guidance or recommendations would be greatly appreciated.

Answer №1

It seems like you are playing with the content but not converting it back to JSON object. Would you need assistance with that?

Perhaps instead of doing jsonData.setIds[i] = new_i; you could use a different approach, such as replacing characters in a string and converting it back for simplicity.

var src = {
    "count": 6909,
    "setIds": [
        "1/7842/0889#001",
        "2/4259/0166#001",
        "ENT0730/0009",
        "9D/11181#002",
        "1/9676/0001#001",
        "2/4718/0001#004",
        "2/1783/0044#001",
        "1/4501/0001#001",
        "1/2028/0002#002",
        "2/3120/0079#001",
        "2/1672/0024#001",
        "2/3398/0064#001"
        //...
    ]
}
var str = JSON.stringify(src, null, 4);
str = str.replace(/\//g,'_').replace(/#/g,'.');
console.log(str);
var res = JSON.parse(str);
console.log(res);

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

Is it normal for a Firebase listener to trigger twice when adding date to the database in React?

I've developed a basic chat application. Once the user submits a message, it is stored in the database along with their username. this.ref.child("/chat").update({username: this.state.username, message: this.state.chatMessage}); Subsequently, I ...

Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so: src/folder1/folder2/m ...

Unable to locate the JSON file for loading in ThreeJS

I am currently attempting to load an external model from Blender onto an Angular app using Three.js. I have been following a tutorial for guidance, found here. However, I have encountered an issue when trying to load the external file: loader.load('. ...

Caution: Server Components can only pass plain objects to Client Components

My app allows users to search for care homes on a map and add new ones using a form. During development, everything was working fine. However, in production, the map was not updating to show the newly added care homes. It seemed that the API fetching the ...

Calculate the total values of nested objects within an array of objects

I encountered an array of objects with various properties - [{ title: "oranges", id: 5802537, cart: { purchased: 3, stockTotal: 9 }, price: 3, department: "fresh fruit and veg" }, { title: &qu ...

Having trouble sending a POST request to a Node.js HTTP Webserver unless it's from the localhost

I am currently facing an issue while attempting to transfer text/data from a client browser to a Node.js webserver. Whenever I try to use any IP address other than localhost, I encounter a "POST ERR_CONNECTION_TIMED_OUT" error. Below is the code snippet f ...

When converting JavaScript to PHP using AJAX, PHP retrieves an empty array

I am attempting to send a file from JavaScript to PHP using AJAX, but PHP is receiving an empty array. Currently, I am working on creating a web page through which I can pass a file to PHP in order for it to access and save information from the file into ...

Refreshing the identification of a button

I have been working on updating an ID with a value from another button. Here is my current progress: $('.viewemployment').on('click', function(e){ var url = '<?php echo Config::get('URL'); ?>dashboard/employmen ...

Tips for sending a Json POST request using Java with Blitline

Hello everyone, I'm currently facing an issue while attempting to send a Json POST request in Java for utilizing the image processing service Blitline. Each time I try, I encounter the following error: IOException: Server returned HTTP response code: ...

Creating an external link in Angular with query parameters

I have created an app where users have their addresses listed, and I want to implement a feature that allows me to open Google Maps when clicking on the address. However, I am currently facing an issue where instead of getting the actual value of {{ this. ...

The anticipated reply was supposed to consist of an array, however it ended up being an

I'm brand new to Angular and I've been searching for a solution to my issue with no luck. My app is supposed to retrieve data from a MongoDB database and display it to the user. However, I keep getting this error message: Error: [$resource:bad ...

the command newman run -k <collection> -e <environment> is experiencing issues and is failing to execute

When running <b>newman</b> with the command <b>newman run -k <collection> -e <environment></b>, the process is encountering an error as shown below:</p> <blockquote> <p>"unable to read data from fi ...

Were you intending to import the file firebase/app/dist/index.cjs.js?

Encountering the following error message: Error: Directory import 'C:\Users\My Name\Documents\Code\WebProjects\nextfire-app\node_modules\firebase\app' is not supported when resolving ES modules import ...

Sending element information to jQuery.post callback function

My goal is to have this.item of an instance of the class filled with data received through the jQuery.post successor function. Currently, I am achieving this by using another user-defined function to set this.item with the received data. Query: Is there a ...

Utilize the setInterval method to repeatedly call the random function

Can someone assist me in setting a time interval of about 1 second for this function? function random_imglink(){ var myimages=new Array() //insert your desired random images below myimages[1]="/documents/templates/bilgiteknolojileri/standalo ...

Tips for displaying and sorting two requests within one console

I am currently working on a project to display both folders and subfolders, but only the folders are visible at the moment. function getParserTypes (types, subject) { return types.map((type) => { return { id: type.entry.id, name: type. ...

The TCP server is cutting off the received message from the network stream

My TCP listener implementation looks like this: Using client As TcpClient = _server.AcceptTcpClient() Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient) Using ns As NetworkStream = client.GetStream() ...

Tips for correctly mapping a shuffled array in React/Next without triggering a hydration mismatch error

I've been working on a Next.js website and I'm trying to display a randomized list of famous quotes. To achieve this, I'm using lodash to shuffle the array of quotes and then mapping them onto the page. import { useMemo } from 'react&ap ...

What are the best practices for ensuring the security of a file upload with Express.js and Formidable?

Looking to enhance security measures for file uploads in NodeJS/Express. How can I ensure that malicious files or code are not uploaded? Currently, the files are simply stored in a folder. This is a basic file upload feature connected to a form on my reac ...

Implement a time interval in a recurring jQuery / Ajax operation

I'm attempting to introduce a delay into a repeating query. After some research, I've discovered that .delay isn't the right approach. Instead, it's recommended to use either setInterval or setTimeout. However, my attempts with both me ...