Home > Software engineering >  How do i automate inserting variables into the given statement?
How do i automate inserting variables into the given statement?

Time:07-02

How do I insert random words in the content line below? for eg : I want to insert hey, hello, hi in

{
    "content": ""
  }

and it prints

{
    "content": "hey"
  }
{
    "content": "hello"
  }
{
    "content": "hi"
  }

CodePudding user response:

You'll have to use Math.random() to get random number between 0 (inclusive) to 3 (exclusive). Then set value to the object by method myObj[property] = value;

let obj = {  };
const randomWordsArr = ["Hey", "Hello", "Hi"];

randomWordsArr.forEach((item)=>{
  const randomNum = Math.floor(Math.random() * randomWordsArr.length);
  
   obj["content"] = randomWordsArr[randomNum];
   console.log(obj);
});

CodePudding user response:

I'm not sure if you're using Python or JS but if it is Python, there are several ways to do this depending on how clean you want it to be. The least clean and fastest option would be to use string manipulation. A better approach would be to maintain a dictionary which will allow you to switch around the value of content as much as you like, after which you can convert the dictionary to Json:

dictionary ={ 
  "content": ""
} 

dictionary["content"] = "hey"
      
json_object = json.dumps(dictionary) 
print(json_object)
  • Related