16

Below is json file. I want to use variables for db password and db username. How can I add a variable in json ?

{
  "name" : "mydb3",
  "storage" : {
    "binaryStorage" : {
      "type"  : "database",
      "driverClass" : "com.mysql.jdbc.Driver",
      "url" : "$jdbcdburl",
      "username" : "$jdbcusername",
      "password" : "$jdbcpassword"
    }
  },
  "workspaces" : {
    "default" : "default",
    "allowCreation" : true
  }
}
Rishi Anand
  • 280
  • 1
  • 4
  • 15

4 Answers4

3

You can either build the JSON up using something like JSON Variables

https://www.npmjs.com/package/json-variables

Or you can load the JSON into memory look for the key and update it, example below using Node.JS

How to update a value in a json file and save it through node.js

Either way you wouldn't have to store the username and passwords in clear text, which is what I am guessing your are trying to avoid?

RickWeb
  • 1,765
  • 2
  • 25
  • 40
1

You may want to try Jsonnet, a data templating language, that is an extension of JSON and can export JSON files. E.g.

{
  person1: {
    username: "Alice",
    password: "abc",
    welcome: "Hello " + self.username + "!",
  },
  person2: self.person1 { username: "Bob", password: "123" },
}

would produce

{
  "person1": {
    "password": "abc",
    "username": "Alice",
    "welcome": "Hello Alice!"
  },
  "person2": {
    "password": "123",
    "username": "Bob",
    "welcome": "Hello Bob!"
  }
}

Other than fields you can also declare variables using local, e.g.

local pi = 3.14;
dimid
  • 7,285
  • 1
  • 46
  • 85
-1

You can use string interpolation + backslash...
See "{{testUrl}}" in Postman exported JSON for exmaple:

Variable value:

  "info":{
    "_postman_id": "YOUR-ID-IN-POSTMAN",
    "name": "YOU-EXPORTED-COLLECTION-FILE-NAME",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
    "testUrl": "https://www.techeader.com"},

Variable implemented in raw:
        "url":{
            "raw": "\"{{testUrl}}\"", 
            "protocol": "http",
            "host": ["test","com"]},
Aviran
  • 15
  • 5
-3

JSON is a standard format for representing objects as a textual, human readable (most of the time :-/ ) format. The concept of a variable is not applicable in this context. Variables exist in memory/code only, and a variable can be written to JSON format in a file for example, but with the risk of sounding "blunt" IMHO, your question doesn't make much sense at this point.

If you elaborate a little more on what you want to achieve in your application, I might be able to help you better.

Wim Van Houts
  • 516
  • 1
  • 8
  • 16