You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript→DynamoDB→嵌入式C流程中换行符处理问题求助

问题解决:嵌入式C中解析JSON转义换行符

你的核心问题是JSON序列化时,换行符被转为了\r\n字面量(即四个ASCII字符:\+r+\+n),嵌入式C读取时没有自动解析这些转义序列,导致它们以可见字符形式存在。以下是两种实用解决方法:


方法1:手动遍历替换转义序列

写一个轻量的C函数,直接遍历字符串,将转义的\r\n替换为实际的控制字符(\r和\n):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void unescape_newlines(char *input, char *output) {
    int in = 0, out = 0;
    while (input[in] != '\0') {
        if (input[in] == '\\') {
            in++;
            if (input[in] == 'r') {
                output[out++] = '\r';
                in++;
                // 处理紧随的\n转义
                if (input[in] == '\\' && input[in+1] == 'n') {
                    output[out++] = '\n';
                    in += 2;
                }
            } else if (input[in] == 'n') {
                output[out++] = '\n';
                in++;
            } else {
                // 保留其他转义字符(如\")
                output[out++] = '\\';
                output[out++] = input[in++];
            }
        } else {
            output[out++] = input[in++];
        }
    }
    output[out] = '\0';
}

int main() {
    char input[] = "-----BEGIN CERTIFICATE-----\\r\\nMIIDCzCCAfMCFENRSInSPfdsalkewqsfdgffdrlijvdssnoawererwq3DQEBCwUAMG4x\\r\\n...";
    char *output = malloc(strlen(input) + 1);
    if (!output) { perror("malloc failed"); return 1; }
    
    unescape_newlines(input, output);
    printf("处理后证书:\n%s\n", output);
    
    free(output);
    return 0;
}

方法2:使用轻量JSON解析库

如果嵌入式系统资源允许,用成熟的轻量JSON库(如cJSON、Jansson)解析数据,这类库会自动处理转义序列,直接返回带实际换行符的原始字符串:

#include <stdio.h>
#include <cjson/cJSON.h>

int main() {
    char json_data[] = "{\"state\":{\"desired\":{\"cert\":\"-----BEGIN CERTIFICATE-----\\r\\nMIIDCzCCAfMCFENRSInSPfdsalkewqsfdgffdrlijvdssnoawererwq3DQEBCwUAMG4x\\r\\n...\"}}}";
    
    cJSON *root = cJSON_Parse(json_data);
    if (!root) {
        printf("JSON解析失败:%s\n", cJSON_GetErrorPtr());
        return 1;
    }
    
    cJSON *cert = cJSON_GetObjectItem(cJSON_GetObjectItem(cJSON_GetObjectItem(root, "state"), "desired"), "cert");
    if (cert && cJSON_IsString(cert)) {
        printf("解析后证书:\n%s\n", cert->valuestring);
        // 此时valuestring已自动替换转义,包含实际换行符
    }
    
    cJSON_Delete(root);
    return 0;
}

额外提示

  • 若嵌入式系统为类Unix环境,可修改替换逻辑只保留\n,忽略\r。
  • 确保输出缓冲区大小足够,避免内存溢出;长字符串建议动态计算所需空间。

内容的提问来源于stack exchange,提问作者monkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:55:23