使用JSON发布.Stringify转换关联数组

Issue using JSON.stringify to convert associative array

本文关键字:关联 数组 转换 Stringify JSON 发布 使用      更新时间:2023-09-26

该问题仅在通过文字定义以编程方式对应关联数组时发生。在字面定义上使用stringify可以工作。

试着去理解,我用这个来测试一个文字定义。

var test = {
    voice : { state : 'Ready' }
};
console.log('Stringify test: ' + JSON.stringify(test));

输出正是我所期望的:

Stringify test: {"voice":{"state":"Ready"}}

当我以编程方式初始化它时,这不会发生。我应该提到,变量是我创建的对象的私有成员,该对象具有访问器/getter方法。在构造函数中,我有:

var states = {};
this.getStates = function()
{
    return states;
}
this.setState = function(newState, mediaType)
{
    states[mediaType] = newState
}

现在我运行相同的测试

customObj.setState('{ state: 'Ready' }', 'voice');
var test = customObj.getStates();
console.log('Stringify test: ' + JSON.stringify(test));

和输出不是我期望的:

Stringify Test: []

最后,我用

再次检查测试变量有什么
for(var x in test)
{
    console.log('State in test: ' + x);
    console.log('Value of ' + x + ': ' + JSON.stringify(test[x])); 
}

我得到:

State in test: voice
Value of voice: {"state":"Ready"}

好的,这告诉我它包含了我所期望的,但是stringify()没有格式化它。现在,我有点糊涂了

我不知道你是如何创建你的customObj,但以下工作:

var CustomObj = function () {
    var states = {};
    this.getStates = function()
    {
        return states;
    }
    this.setState = function(newState, mediaType)
    {
        states[mediaType] = newState
    }
};
var customObj = new CustomObj();
customObj.setState({ state: 'Ready' }, 'voice');
var test = customObj.getStates();
console.log('Stringify test: ' + JSON.stringify(test));

输出:

Stringify test: {"voice":{"state":"Ready"}}