0

An example sketch I found online to post an HTTP request using arduino contains the following code

String payload_pattern = "{'id':'MyESP','sensors':[{'id': 'Temperature','data': $temperature$},
{'id':'Humidity','value': $humidity$},{'id': 'Counter','value': $counter$}]}";

Further down in the sketch

counter += 1;
 float temperature = 23.456;
 float humidity = 80.21;
 String payload = payload_pattern;
 payload.replace("$temperature$",String(temperature));
 payload.replace("$humidity$",String(humidity));
 payload.replace("$counter$",String(counter));

What I don't understand is the $variable$ syntax. I assume it will substitute the actual value of the variables later but I haven't seen such syntax before. Initially I thought its a way of referencing just like using the ampersand operator but not sure. Also I couldn't find much info on the web. Could you please explain what that syntax is and what is it called?

  • 3
    It's not syntax. replace will replace any string. Adding a dollar sign to the beginning and end is how this particular author chose to mark the strings he intended to replace. He could have used anything. He could have simply used the word counter instead of $counter$ but that might have appeared somewhere else in the string and it would have replaced the wrong one. So he chose something that probably wouldn't show up that often by itself. Words with dollar signs on either end. – Delta_G May 24 at 0:16
  • instead of wondering about the unknown $counter$ syntax, determine what this function does payload.replace("$counter$",String(counter)); – jsotola May 24 at 1:04
  • 1
    Note that: 1. This payload looks a lot like JSON but is not: valid JSON should have double quotes instead of single quotes. 2. The data fields are called “value”, except for the temperature which is called “data”, which is somewhat inconsistent. – Edgar Bonet May 24 at 8:51
  • @Delta_G Thanks for clarification. I was wondering if the $ symbol is necessary or part of special syntax and can I simply use the variable names to make it work. But it makes sense now :) – Zaffresky May 24 at 10:01
  • 1
    @jsotola I already looked it up to see what it does but since my limited experience with C language is in the context of writing arduino sketches and sometimes I come across special syntaxes or shorthands that are typical of programmers experienced in C. So I was curious about that "unknown" syntax – Zaffresky May 24 at 10:09

Your Answer

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

Browse other questions tagged or ask your own question.