I have a contract with different categories. We can assume them to be the following here:

  1. Cities
  2. Countries
  3. Counties

Suppose I want to add a new city to the category cities. I'm assuming this has to be an array as I need to be iterable.

This code does not compile but it shows the type of thing I want to achieve

mapping(string => string[]) Categories;
// Add a record
function addCity(string _type, string _city) {

I will need these strings (the cities) to be passed around and apparently that is not possible in Ethereum yet (see here).

Alternatively, I tried doing this (omitting irrelevant code)

mapping(string => bytes32[]) Categories;
function addCity(string _type, bytes32 _city) {

Which does compile. However, when I add


I get back


and I don't know what to do to convert it to 599437d068e6196203c2ec23 when fetching the value. I've tried web3.toAscii() but it didn't work.

My question is: is there an alternative way which I'm missing or, if not, how to I convert the value back when I need to?


toAscii gives me the result that it looks like you were expecting, after stripping out the 0-padding:

> hex_val = '0x3539393433376430363865363139363230336332656332330000000000000000'
> padded_str = web3.toAscii(hex_val)
> first_null = padded_str.indexOf('\x00')
> trimmed_str = padded_str.slice(0, first_null)
  • I should be clear that this does not work if you have any null bytes inside your string. In most encodings, null byte is used to signify the end of the string, so you should be safe as long as you're using one of those encodings. (like the most common one, and Solidity default: UTF-8) – carver Aug 16 '17 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.