1

I have the following JSON,

{
  "commands": [
    {
      "command":"begin ${{password}}",
      "name":"Initialization",
      "description":"Send SMS begin+password"
    }
  ]
}

How can I pass data to ${{password}} to get the filled string using the passed value?

I tried to use interpolation function as described on the following topic but without any success.

Convert a string to a template string

Does Angular, Ionic provide some built-in functions for this?

INDRAJITH EKANAYAKE
  • 3,894
  • 11
  • 41
  • 63
redrom
  • 11,502
  • 31
  • 157
  • 264
  • You made up this JSON or you are getting it from somwhere? – nice_dev Apr 24 '19 at 11:11
  • I'm able to edit the JSON file. – redrom Apr 24 '19 at 11:29
  • But JSON with using single quotes is not valid JSON. "command":'begin ${password}'. I want to set variable to class scope and print JSON value to template. Interpolated value in JSON should be replaced by the value set in the Class Scope. – redrom Apr 24 '19 at 12:08

2 Answers2

1

var password = 'StackOverflow';
var json_string = `{
  "commands": [
    {
      "command":"begin ${password}",
      "name":"Initialization",
      "description":"Send SMS begin+password"
    }
  ]
}`;

console.log(json_string);

Well, you could just use backticks (``) and make it a template string, since you could edit the json file as discussed in the comments. Also, you need to have placeholders for variable's value to take effect. So change ${{password}} to ${password}.

nice_dev
  • 17,053
  • 2
  • 21
  • 35
  • Thanks for code snippet, but seems that JSON content cannot be attached dynamically. private modifyData(data:any) { let json_string = ``+JSON.stringify(data)+``; return JSON.parse(json_string); Does not changing data in placeholders. – redrom Apr 24 '19 at 14:10
  • @redrom You have the json data in a file. So, have backticks and placeholder changes in the file there and read it in your `modifyData()`. – nice_dev Apr 24 '19 at 14:13
0

After some digging around solved using replace in this way:

{
  "commands": [
    {
      "command":"begin |password| and |ipAddress|",
      "name":"Initialization",
      "description":"Send SMS begin+password"
    }
  ]
}

private modifyData(data:any) {
    let stringifiedData  = JSON.stringify(data).replace("|password|", this.password).replace("|ipAddress|", this.ipAddress);
    return JSON.parse(stringifiedData);
  }

Result: enter image description here

redrom
  • 11,502
  • 31
  • 157
  • 264