Merging values of different keys in a .json file

Check out my json file below:

{
    "foo": "https://3a1821d0.ngrok.io/api/foo",
    "bar": "https://3a1821d0.ngrok.io/api/bar",
}

I am interested in changing the key 3a1821d0 to a different variable within the json structure, like so:

{
    "some_variable": 3a1821d0,
},
{
    "foo": "https://some_variable.ngrok.io/api/foo",
    "bar": "https://some_variable.ngrok.io/api/bar",
}

Wondering if this is doable? And if it is, what would be the process for achieving it?

Answer №1

To prevent any conflicts with the replacement, I suggest enclosing the occurrences you wish to replace within [] or another character of your choice. Save your file as data.json and here is an example of its contents:

{
    "some_variable": "3a1821d0",
    "foo": "https://[some_variable].ngrok.io/api/foo",
    "bar": "https://[some_variable].ngrok.io/api/bar"
}

If you are working with Node.js, this script will help you accomplish the task.

const fs = require('fs');

let fileData = fs.readFileSync('data.json', "utf-8");

let jsonContent = JSON.parse(fileData);
const someVar = jsonContent.some_variable;

// Adding null and 4 helps maintain the file's format
let jsonDataStr = JSON.stringify(jsonContent, null, 4);

// Replace all instances of [some_variable] with the content of "some_variable"
jsonDataStr = jsonDataStr.split('[some_variable]').join(someVar);

// Rewrite the file
fs.writeFileSync('output.json', jsonDataStr);

Answer №2

Here is a technique you can utilize to substitute a matched content with your preferred content. Just switch test with the text you want.

let data ={
    "foo": "https://3a1821d0.ngrok.io/api/foo",
    "bar": "https://3a1821d0.ngrok.io/api/bar",
}

Object.keys(data).forEach(key => data[key] = data[key].replace(/3a1821d0/,"test"))
console.log(data)

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

Determining the victorious player in a game of Blackjack

After the player clicks "stand" in my blackjack game, my program checks for a winner. I am using AJAX to determine if there is a winner. If there is a winner, an alert will display their name. Otherwise, the dealer will proceed with making their move. Any ...

Utilizing jq to iterate through JSON and perform replacements

UPDATE: After reassessing my initial question, I have found that I can extract all the necessary data in one API call. The JSON response from my API call is as follows: { "lights": { "8": { "name": &qu ...

Ways to create a fixed top navigation bar that adjusts content similarly to a non-fixed navbar

I'm looking to achieve a fixed navbar at the top that pushes down content when I open the collapse menu, similar to how it functions in static or regular navbars. Something like this example: (https://getbootstrap.com/examples/navbar-static-top/) but ...

What is the reason for this JavaScript code not activating the input field (aspx)?

Thank you for taking the time to review this. I understand that for most of you client side scripting experts, this task is a breeze. However, all I am trying to achieve is to display a message at the top notifying the user that their click has been regist ...

Could this be a problem with synchronization? Utilizing Google Translate to link-translate terms

Trying to create a script that will show how a word changes through multiple translations using Google Translate, but struggling with Javascript. The problem I'm facing is hard to pinpoint: function initialize() { var word = "Hello"; var engl ...

Learn the process of implementing multiple onClick listeners in React without deleting the existing ones

I'm facing a tricky situation with adding multiple event listeners based on different conditions. When the first condition is met, I attach a function to the click event: ref.current.onclick = ()=> {function1()} However, when the second condition ...

"Executing the ajax send() function does not result in any changes to the

Just starting to explore ajax and I need some help. Can anyone explain why the address bar is not updating when using ajax send()? The connection is working, but it keeps displaying "There is no variable!" PS: Please note that I prefer not to use JQuery. ...

What is the best way to merge and nest connected JSON elements?

I am working with two separate JSON files that I need to merge into one single JSON object for use on the frontend of my project. fragments.json [ { "id": 2, "title": "John Smith is nice", "reports& ...

How to use Angular 8 HttpClient to set JSON headers

When I attempt to send a JSON object using Angular 8 HttpClient to an ASP.net Core backend, the following code is used: import { HttpClient, HttpHeaders} from '@angular/common/http'; import { User } from '@/_models'; login(usernam ...

Automated pagination integrated with automatic refreshing of div every few seconds

I am currently working on setting up a datatable and I need it to be displayed on the monitor in such a way that it can refresh the div and automatically paginate to the next page. However, whenever the div is refreshed, the auto-pagination gets cancelle ...

What is the best way to create this server backend route?

I'm currently working on a fullstack project that requires a specific sequence of events to take place: When a user submits an event: A request is sent to the backend server The server then initiates a function for processing This function should ru ...

unable to locate the font file I recently downloaded in the Windows terminal

Interested in customizing your Windows terminal? I recently decided to change my font style and downloaded the desired one. However, despite seeing the font in control panel and trying the "downloading for every user" option, my terminal still can't l ...

What are the best ways to handle JSON data in Python and Bash?

Having trouble parsing the JSON data below using Bash and Python. Errors are popping up. I am trying to extract the name and ObjectID information from the JSON and store it in an array, but I'm not sure how to accomplish this. Sample JSON: { ...

retrieve the chosen option from the dropdown menu

Whenever I try to display the input type based on the selection from a select element, I encounter an issue Here is the select element within my view: <select id="type" name="type_id" class="form-control" required> @foreach($type as $row) & ...

Troubleshooting Angular 2 ng-if issues

Is there a way to dynamically apply CSS styles to an element that has an ng-if condition, even if the condition fails? It currently works fine when the condition is true, but I'm looking for a solution that allows me to modify the element regardless o ...

Modifying an object's attribute in React.js by toggling a checkbox

As I delve into learning React, I am constructing a straightforward todo list. Here's the object contained within my initialState: getInitialState:function(){ return { items: [ { text:"Buy Fish", ...

If the ID (i.e. document.getElementById) is not found, then keep JavaScript running

I'm currently working on a JavaScript project where I need the script to gracefully handle missing div-ids and continue executing. I've looked into various solutions, but many involve either replacing the missing ID or placing information into an ...

Employ the JSON body within the SOAP envelope when transmitting data to a WCF service

Is it feasible to incorporate a soap header for authentication into a json body? The contract has been defined as follows: [ServiceContract(Namespace = "http://tourico.com/webservices/hotelv3")] public interface IHotelMobileFlow { [OperationContract, ...

Error TS2307: Module 'calculator' could not be located

Running a Sharepoint Framework project in Visual Studio Code: This is the project structure: https://i.stack.imgur.com/GAlsX.png The files are organized as follows: ComplexCalculator.ts export class ComplexCalculator { public sqr(v1: number): number ...

The third page of Reddit's JSON data on display

When utilizing the Reddit api, I have found a way to retrieve the json of a page. I have successfully done this for the front page, but now I am wondering how to obtain the json for the third page without navigating through the second page. Is there a met ...