json_encode.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
  2. // Copyright (c) 2013 Cesanta Software Limited
  3. // All rights reserved
  4. //
  5. // This library is dual-licensed: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License version 2 as
  7. // published by the Free Software Foundation. For the terms of this
  8. // license, see <http://www.gnu.org/licenses/>.
  9. //
  10. // You are free to use this library under the terms of the GNU General
  11. // Public License, but WITHOUT ANY WARRANTY; without even the implied
  12. // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. // See the GNU General Public License for more details.
  14. //
  15. // Alternatively, you can license this library under a commercial
  16. // license, as set out in <http://cesanta.com/products.html>.
  17. // json encoder 'frozen' from https://github.com/cesanta/frozen
  18. #include <stdio.h>
  19. #include "json_encode.h"
  20. int json_emit_int(char *buf, int buf_len, long int value) {
  21. return buf_len <= 0 ? 0 : snprintf(buf, buf_len, "%ld", value);
  22. }
  23. int json_emit_double(char *buf, int buf_len, double value) {
  24. return buf_len <= 0 ? 0 : snprintf(buf, buf_len, "%g", value);
  25. }
  26. int json_emit_quoted_str(char *buf, int buf_len, const char *str) {
  27. int i = 0, j = 0, ch;
  28. #define EMIT(x) do { if (j < buf_len) buf[j++] = x; } while (0)
  29. EMIT('"');
  30. while ((ch = str[i++]) != '\0' && j < buf_len) {
  31. switch (ch) {
  32. case '"': EMIT('\\'); EMIT('"'); break;
  33. case '\\': EMIT('\\'); EMIT('\\'); break;
  34. case '\b': EMIT('\\'); EMIT('b'); break;
  35. case '\f': EMIT('\\'); EMIT('f'); break;
  36. case '\n': EMIT('\\'); EMIT('n'); break;
  37. case '\r': EMIT('\\'); EMIT('r'); break;
  38. case '\t': EMIT('\\'); EMIT('t'); break;
  39. default: EMIT(ch);
  40. }
  41. }
  42. EMIT('"');
  43. EMIT(0);
  44. return j == 0 ? 0 : j - 1;
  45. }
  46. int json_emit_raw_str(char *buf, int buf_len, const char *str) {
  47. return buf_len <= 0 ? 0 : snprintf(buf, buf_len, "%s", str);
  48. }