Is it possible to use abbreviations instead of full names for object properties in a JSON string?

I'm looking for a way to efficiently convert large and repetitive javascript objects into JSON strings. With the abundance of repeating property names in these objects, I want to streamline the process by replacing those names with predefined abbreviations from a mapping list. My initial idea was to utilize the replacer function within JSON.stringify to skip the step of creating the JSON string first and then manipulating it, or altering the original object's property names directly, but I have yet to find out how to do this.

For instance, considering the following mapping of property names to abbreviations:

var map = {
    prop0: "p0",
    prop1: "p1",
    prop2: "p2"
}

I aim to transform an object like the one below:

var obj = {
    prop0: "value0",
    prop1: [
        {prop2: "value2"},
        {prop2: "value3"},
        {prop2: "value4"}
    ]
}

into a JSON string resembling this:

{"p0":"value0","p1":[{"p2":"value2"},{"p2":"value3"},{"p2":"value4"}]}

and vice versa.

Answer №1

While there are various methods for compressing JSON data, one approach involves utilizing the JSON.parse reviver and the JSON.stringify replacer to manipulate nested values. It's important to note that this particular example may not function correctly in Internet Explorer:

var obj = { prop0: "value0", prop1: [ { prop2: "value2" }, { prop2: "value3" }, { prop2: "value4" } ] }

var replacer = map => (k, v) => v.constructor !== Object ? v : 
  Object.fromEntries( Object.entries(v).map(([k, v]) => [map[k] || k, v]) )

var json = JSON.stringify(obj, replacer({ prop0: "p0", prop1: "p1", prop2: "p2" }))

var obj2 = JSON.parse(json, replacer({ p0: "prop0", p1: "prop1", p2: "prop2" }))

console.log( json )
console.log( obj2 )

Answer №2

If there are no more nested values, you might want to consider implementing a solution similar to the following:

var mapping = {
  prop0: "p0",
  prop1: "p1",
  prop2: "p2"
}

var object = {
  prop0: "value0",
  prop1: [
    { prop2: "value2" },
    { prop2: "value3" },
    { prop2: "value4" }
  ]
}

const newObject = {};

for (let key in object) {
  if (Array.isArray(object[key])) {
    newObject[mapping[key]] = object[key].map(item => {
      const arrKey = Object.keys(item)[0];
      return {
        [mapping[arrKey]]: item[arrKey]
      }
    })
  } else {
    newObject[mapping[key]] = object[key]
  }
}

console.log(JSON.stringify(newObject))

Answer №3

If you're looking to efficiently organize and transform your data, consider utilizing the Json Data Mapper node module available on npm at Json data mapper.

This tool enables you to define a custom schema and seamlessly convert your data into the desired format.

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

choose based on attributes within sub-array

I'm currently working on automating the process of updating AWS Lambda layers and the associated functions. To identify the functions using a specific layer, I am parsing the JSON output from the AWS CLI when listing all the functions in my AWS accoun ...

Building an Angular 4 universal application using @angular/cli and integrating third-party libraries/components for compilation

While attempting to incorporate server side rendering using angular universal, I referenced a post on implementing an angular-4-universal-app-with-angular-cli and also looked at the cli-universal-demo project. However, I ran into the following issue: Upon ...

What is the method to convert Javascript values from pixels to percentages?

Is it possible to change the scrolltop value dynamically based on a percentage of the user's screen size? I've been trying to achieve this using JS but haven't had any luck. Here is a link to a codepen that showcases the issue: [link] (http ...

Is there a way to run Angular code without having to bootstrap it?

Typical manual bootstrapping examples often use the same pattern: angular.module('myApp', []); angular.bootstrap(document, ['myApp']); However, I only need Angular to trigger a popup using the ui-bootstrap module. The closest solutio ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

Attempting to activate an ASP button that is created within a gridview after pressing the enter key within a textbox

I am currently working on a gridview with dynamically generated rows, each row containing text boxes and buttons. The goal is to update the database with values from the textboxes when UpdateBtn1 is clicked. Users should be able to either click the button ...

Turning JSON into Base64 Before Sending it via HTTP POST (using Haskell)

Challenge: I'm facing an issue while sending JSON data via HTTP POST request, as the endpoint I am using only accepts Base64 encoding. Sample Code: Here's a snippet of code that successfully sends the JSON data without Base64 encoding: {-# LANG ...

What is the process for configuring a headless implementation of three.js on a node server, similar to the babylon.js-NulEngine setup?

My current project involves the development of a multiplayer three.js fps game, with client-side prediction in the browser. For the server-side implementation, I am utilizing Node.js Express.js and Socket.io for handling authoritative functions such as col ...

Dynamic loading of tinymce in progress

When tinymce is loaded in the head and before dom, everything works fine. However, if I attempt to load the JavaScript with ajax using jquery.getScript(), it doesn't work. I initialize tinymce when the user clicks the content area, so the dom must be ...

Can the security of a JSON file function as a database be relied upon?

I'm curious about the security of using a json file as a database on our local computer. Is it more secure than using SQL? ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...

Resolving the dilemma of complete form validation in Jquery

I'm currently working on a PHP form that is being validated with jQuery. In this form, there is a radio button list. If the user clicks "Yes," then the textbox related to that radio button should not be validated. However, if the user clicks "No," the ...

Having Trouble Using Fetch API with ASP.NET Core 2 Controllers that Require Authorization

I have the following code on the client side: fetch("/music/index", { headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { throw response; } return response.json(); }) ...

Having Multiple Login Forms on a Single Page

I have encountered an issue with my login form code. It works perfectly as a single form, but I need to have 20 of these forms on one page. Despite my efforts to duplicate the code for each new form and adjusting the IDs, I am unable to make more than one ...

Express routes are malfunctioning

I have a situation with two different routes: /emails and /eamils/:id: function createRouter() { let router = express.Router(); router.route('/emails/:id').get((req, res) => { console.log('Route for get /emails/id'); }); ...

Navigating pages with Jqueryor Using J

Currently, I am utilizing jQuery and AJAX to retrieve data from a remotely stored PHP file on a server. After successfully fetching the initial page and displaying the outcomes in an HTML table, I've encountered a new challenge. My goal now is to fetc ...

Converting PHP variables to JavaScript variables: A step-by-step guide

I'm trying to figure out the most efficient method for retrieving PHP variables using AJAX and then transforming them into JavaScript variables. Imagine I have the following code in my PHP file: echo $total; echo $actual; Edit: JSON echo json_enco ...

Javascript - Unable to update button text

I am encountering a problem with updating the text of a Bootstrap button when a collapsed element is opened or closed. The icon part is updating successfully, but I am struggling to get the button text to update and I cannot figure out why. My knowledge o ...

Is there a way for me to receive notifications about errors while piping to gulp browserify?

I am leveraging browserify to utilize npm modules in my front end code, and I use gulp for my build tasks. The setup is functioning smoothly: const browserify = require('gulp-browserify'); gulp.task('js', ['clean'], function ...

Illustrative demonstration of AngularJS

One way to showcase data using AngularJS is by triggering a function with a button click. Here's an example: <!DOCTYPE html> <html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"& ...