-4

I want to change string to variable, please some one help me. this is a string >> {"method":"setValue","params":{"cmd_Motor":true}}

I wan to change like this:

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Ngoc Auto
  • 1
  • 1
  • I want to convert like this: https://imgur.com/O3miplm – Ngoc Auto Aug 03 '23 at 13:22
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse – Andy Aug 03 '23 at 13:25
  • Looks like the question actually should be why is request.body a string and not an object. http://expressjs.com/en/resources/middleware/body-parser.html or the request is not setting the correct content type. – epascarello Aug 03 '23 at 13:32

2 Answers2

0

Use JSON.parse()

const input = '{"method":"setValue","params":{"cmd_Motor":true}}';
const result = JSON.parse(input);
entio
  • 3,816
  • 1
  • 24
  • 39
0

I am not sure if I understood your question, but you can convert a string to a JSON object and you can also convert a JSON object to a string:

converting from string to json

const myString = '{"method":"setValue","params":{"cmd_Motor":true}}';
const myJson = JSON.parse(myString);

console.log(myJson.method) // setValue
console.log(myJson.params.cmd_Motor) // true

converting from json to string

const myJson = { method: 'setValue', params: { cmd_Motor: true } };
const myString = JSON.stringify(myJson);

console.log(myString);
MeerArtefakt
  • 386
  • 2
  • 6
  • 26