JSON.parse存在什么困难?

3

我已经和我的开发小黄鸭交谈了几个小时,但是我就是不能使用小黄鸭调试这段代码。基本上,它会返回 JSON 子对象的 [object Object]。有趣的是,如果我复制并粘贴记录下来的未解析的 JSON 文本,然后进行解析,它就可以正常解析。

以下是代码示例及输入值:

/*
We are feeding in:
{
    'src' : './template.html',
    'format' : 'plain',
    'input' : {
        'noun' : 'World'
    },
    'replace' : 'templateExampleSkeleton'
}
*/

// Locals.
let tmpScripts:Array<string> = [];
let tmpScriptIds:Array<string> = [];
let tmpStrings:Array<string> = [];
let tmpStringIds:Array<string> = [];

// Replace scripts with placeholder IDs, and store their contents in a temporary location.
// They will be restored later, because they would cause issues with the JSON parser.
// This isn't used in this case but is used in general.
args = args.replace(/js{{(.|\s)*}}/g, (substring:string) => {
    let tmpScriptId:string = this.#utils.genRandomId(false, tmpScriptIds);
    tmpScripts.push(substring.replace('js{{','').replace('}}',''));
    return `%%{{${tmpScriptId}}}%%`;
})

// Replace 's with "s.
.replace(/'/gm, '"')

// Replace whitespace.
.replace(/(\s|\n|\t|\r)*/gm, '')

// Restore the strings using their IDs.
.replace(/##{{.{32}}}##/gm, (substring:string) => {
    let tmpStringValue:string = '';
    tmpStringIds.forEach((id:string, i:number) => {
        if (substring.includes(id)) tmpStringValue = tmpStrings[i];
    });
    return tmpStringValue;
});

// Add curly brackets so that the JSON parser doesn't yell.
args = '{' + args + '}';

console.log(args); // ==> {"src":"./template.html","format":"plain","input":{"noun":"World"},"replace":"templateExampleSkeleton"}

// Parse the arguments as JSON.
let argsJson = JSON.parse(args);

// Using the new object, iterate through its keys in order to
// restore the scripts that were removed for parsing as JSON.
// This isn't(?) used in this case but is used in general.
Object.keys(argsJson).forEach((argKey, i) => {
    argsJson[argKey] = argsJson[argKey].toString().replace(/%%{{.*}}%%/gm, (substring:string) => {
        substring = substring.replace(/%%{{/, '').replace(/}}%%/, '');
        let tmpScriptValue:string = '';
        tmpScriptIds.forEach((id:string, i:number) => {
            if (id === substring) tmpScriptValue = tmpScripts[i];
        });
        return tmpScriptValue;
    });
});
// Log the object for debug.
console.log(argsJson); // ==> Object { src: "./template.html", format: "plain", input: "[object Object]", replace: "templateExampleSkeleton" }

非常感谢任何帮助:^)

这里的实际问题是什么?为什么你不首先使用有效的JSON而要做所有这些事情呢? - Pointy
@Pointy 嘿,我应该提到一下,“JSON”在HTML属性中。 - LostEth0
2
好的,如果一切都以有效的JSON格式开始,那么一切都会简单得多。 - Pointy
2
这将涉及到您在键的foreach中的'argsJson [argKey] .toString()'。因为在此之前,您的“JSON”对象已被解析为JavaScript对象。在JavaScript对象上调用toString()会返回字符串“[object Object]”。 - Lex Webb
@LexWebb哦,我怎么会错过那个?非常感谢,现在已经修复了:Object.keys(argsJson).forEach((argKey, i) => { if (typeof argsJson[argKey] === 'string') { ... } }); - LostEth0
2
@LostEth0 没问题!也许是时候退役你的调试鸭子,换一款更新的模型了!;) - Lex Webb
1个回答

0

为了用一个答案关闭这个问题,正如@LexWebb所指出的:

Object.keys(argsJson).forEach((argKey, i) => {
    argsJson[argKey] = argsJson[argKey].toString().replace(/%%{{.*}}%%/gm, (substring:string) => {
        substring = substring.replace(/%%{{/, '').replace(/}}%%/, '');
        let tmpScriptValue:string = '';
        tmpScriptIds.forEach((id:string, i:number) => {
            if (id === substring) tmpScriptValue = tmpScripts[i];
        });
        return tmpScriptValue;
    });
});

应该是:

Object.keys(argsJson).forEach((argKey, i) => {
    if (typeof argsJson[argKey] === 'string') {
        argsJson[argKey] = argsJson[argKey].replace(/%%{{.*}}%%/gm, (substring:string) => {
            substring = substring.replace(/%%{{/, '').replace(/}}%%/, '');
            let tmpScriptValue:string = '';
            tmpScriptIds.forEach((id:string, i:number) => {
                if (id === substring) tmpScriptValue = tmpScripts[i];
            });
            return tmpScriptValue;
        });
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接