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?

3
  • You made up this JSON or you are getting it from somwhere? Commented Apr 24, 2019 at 11:11
  • I'm able to edit the JSON file. Commented Apr 24, 2019 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. Commented Apr 24, 2019 at 12:08

2 Answers 2

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}.

Sign up to request clarification or add additional context in comments.

2 Comments

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 You have the json data in a file. So, have backticks and placeholder changes in the file there and read it in your modifyData().
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

1 Comment

This isn't technically templating but a simple string replace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.