3

I need a JSON like this:

{meteo: 'Fluorine', commento: 'F'}

but when I use get function I receive this:

[ '1meteo', '1commento', meteo: '1meteo', commento: '1commento' ]

I'm using Express for the backend, this is my code:

app.get('/getallgiornale', async function (req, res) {

  // Get the contract instance.
  const networkId = await web3.eth.net.getId();
  const deployedNetwork = Giornaledeilavori.networks[networkId];
  const instance = new web3.eth.Contract( Giornaledeilavori.abi, deployedNetwork && deployedNetwork.address );

  // getAll
  const response = await instance.methods.getAll().call();
  res.send(response);

});

and in Solidity:

contract Giornaledeilavori {
struct Dati{
string meteo;
string commento;
}
Dati[] public dati;

//getAll function:
function getAll() public returns (Dati[] memory){
  Dati[] memory d = dati;
  return d;
}

//set function:
  function setDato(string memory _meteo, string memory _commento) public  {
    Dati memory newDati = Dati({
    meteo: _meteo,
    commento: _commento
  });
    dati.push(newDati);
}

set function in Express is like this:


app.get('/setgiornale', async function (req, res) {
  var accounts = await web3.eth.getAccounts();
  // Get the contract instance.
  const networkId = await web3.eth.net.getId();
  const deployedNetwork = Giornaledeilavori.networks[networkId];
  const instance = new web3.eth.Contract( Giornaledeilavori.abi, deployedNetwork && deployedNetwork.address );

  // setDati
  instance.methods.setDato('1meteo','1commento').send({
    from: accounts[0],
    gas:"4500000",
    privateFor:['ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=']
  },(error, transactionHash) => {
    if(error) {
      console.log(error);
      res.send(500);
    } else {
      res.send(transactionHash);
    }
  });
})

In the set function I tried to use json instead of send but it didn't work. I used json stringify but it didn't work.

How can I receive a json?

Thank you for answers.

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
Francesco Bocci
  • 827
  • 8
  • 19

1 Answers1

2

You should return json format in your node server:

return res.json({ questions: questions });

Also you are received array response because of this line

dati.push(newDati);
Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
  • 1
    I know but I recieve this response: `[ '1meteo', '1commento', meteo: '1meteo', commento: '1commento' ]`, not this: ` { questions: questions }` – Francesco Bocci May 20 '19 at 11:29
  • Just updated my answer. You need to find a way to change the response because you are push your data into an array – Tony Ngo May 20 '19 at 11:31
  • Try this link to see if it work for you https://stackoverflow.com/questions/2295496/convert-array-to-json – Tony Ngo May 20 '19 at 11:32