[Ethereum] How to serialize an array of strings in Solidity

contract-debuggingcontract-designcontract-developmentsolidity

Since I can't seem to get my contract to return a string array in any of its methods, I'm just going to serialize the array and return it as a string or bytes.

I've tried various for loop methods to do this but I can't seem to concatenate strings either.

What's the best way to serialize an array of strings in Solidity?

I have a function like this that isn't working:

/* inside my contract */

string[] myArray;

function serializeArray() returns (string serializedArray) {
  uint arrayLength = myArray.length;
  string serialized = '[';

  for (uint i = 0; i < arrayLength; i++) {
    serialized += '"';
    serialized += inbox[i];
    serialized += '"';

    if (i < arrayLength) {
      serialized += ',';
    }
  }
  serialized += ']';

  return serialized;
}

Best Answer

This is not going to work in Solidity. The += operator is not implemented for strings, you need to use a library that allows to concatenate strings; I think the most popular is this one. There is an example of how to use concatenation here.

I'm not sure what you're trying to do, but that kind of concatenation is expensive. Wouldn't it be enough to have two methods:

getStringsLength() returns (uint) and getStringByIndex(uint index) returns (string), and retrieve the strings in a loop? You can then do the concatenation outside of the contract (probably cheaper).

Solidity:

string[] myArray;

function getStringsLength() returns (uint) {
    return myArray.length;
}

function getStringByIndex(uint index) returns (string) {
    if (index < myArray.length){
        return myArray[index];
    }
    return "";
}

Solidity-consumer pseudocode:

strings_to_serialize = []
for (int i=0; i<contract.getStringsLength(); i++)
    strings_to_serialize.append(contract.getStringByIndex(i))
# process the strings here
Related Topic