Open In App

Add Nested JSON Object in Postman

Last Updated : 27 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Postman is a helpful tool for testing APIs and working with JSON. It lets you add nested objects to existing JSON. JSON is a simple data format for both humans and machines. Postman also lets developers send requests and view responses, which is really useful for working with JSON data.

These are the following approaches to add Nested JSON object:

Manually define the nested structure

  • In your request, go to the "Body" tab.
  • Select "raw" mode and choose "JSON (application/json)" from the dropdown menu. This ensures Postman interprets the data as JSON.
  • Start defining your main object with key-value pairs.
  • For nested objects, use curly braces {} within a key's value.

Within these curly braces, define the nested object's key-value pairs. You can further nest objects within these nested objects for complex structures.

Example: A JSON object representing a person named john doe and his address.

{
"name": "John Doe",
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
}
}
hii
In this example, "address" is a nested object within the main object with its own key-value pairs.

Leverage pre-request scripts

  • Go to the "Tests" tab in your request.
  • Click on "Pre-request Script" .
  • Use libraries like JSON.parse and JSON.stringify to manipulate existing JSON data.

You can parse existing JSON from a file or environment variable. Build the desired nested object structure within the script. Use JSON.stringify to convert the manipulated data back to a JSON string.

Example: Parse the request body to JSON, add a nested object under a new key, and convert it back to a string. Update the request body in raw JSON format with the modified data.

// Define your nested object
let jsonData = JSON.parse( pm.request.body);
let nestedObject = {
"info": {
"description": "This is some nested data"
}
}

// Add the nested object to your main data
jsonData.data = nestedObject;

jsonData = JSON.stringify(jsonData);



let body = {
mode: 'raw',
raw:jsonData,
options: {
raw: {
language: 'json'
}
}
}
pm.request.body.update(body);
23
adding nested data by pre-request script

Next Article

Similar Reads