【问题标题】:JSON.stringify does not convert arraysJSON.stringify 不转换数组
【发布时间】:2015-04-13 15:11:22
【问题描述】:

我知道我的做法是错误的,老实说,这可能是因为我错误地处理了递归,但如果是这样,我不确定我哪里出错了。这是example的链接。

这里是 JavaScript -

function propertyTest(currentObject, key) {
    for (var property in currentObject) {
        if (typeof currentObject[property] === "object") {
            propertyTest(currentObject[property], property);
        } else {
            // this is only to test the output
            $('#method1').append((property == 'value' && key ? key : property) + ' -- ' + currentObject[property] + '<br />');
            propertyKey = (property == 'value' && key ? key : property);
            propertyValue = currentObject[property];
            var arrayJSON = [];
            arrayJSON.push(propertyKey);
            arrayJSON.push(propertyValue);
        }
    }
    var JSONString = JSON.stringify(arrayJSON);
    console.log(JSONString);
    return JSONString;
}

这是原始 JSON -

var oarsObject = [{
    "coordinateReferenceSystem": "26782,15851",
    "positionReferenceType": "geogWgs84",
    "geogWgs84": {
        "latitude": {
            "value": 0.50507158458214041
        },
        "longitude": {
            "value": -1.604064725846865
        },
        "height": {
            "value": 0.0
        }
    }
}, {
    "coordinateReferenceSystem": "26782,15851",
    "positionReferenceType": "geogWgs84",
    "geogWgs84": {
        "latitude": {
            "value": 0.50509265195620767
        },
        "longitude": {
            "value": -1.5961047836759397
        },
        "height": {
            "value": 0.0
        }
    }
}, {
    "coordinateReferenceSystem": "26782,15851",
    "positionReferenceType": "geogWgs84",
    "geogWgs84": {
        "latitude": {
            "value": 0.4963464715653228
        },
        "longitude": {
            "value": -1.5960947041991222
        },
        "height": {
            "value": 0.0
        }
    }
}, {
    "coordinateReferenceSystem": "26782,15851",
    "positionReferenceType": "geogWgs84",
    "geogWgs84": {
        "latitude": {
            "value": 0.49632551101280209
        },
        "longitude": {
            "value": -1.604015267530267
        },
        "height": {
            "value": 0.0
        }
    }
}]

JSON 会按照您的预期发送到函数 -

propertyTest(oarsObject);

这是它偏离轨道的证据,来自控制台的 sn-p -

["latitude",0.5050715845821404]
["longitude",-1.604064725846865]
["height",0]
undefined
["positionReferenceType","geogWgs84"]
["latitude",0.5050926519562077]
["longitude",-1.5961047836759397]
["height",0]
undefined

注意前两项最初是如何出现在日志中的,然后才出现positionReferenceType。另请注意 undefined JSON 字符串。我确定这是因为我的递归错误。

我知道 JavaScript 数组需要数字键在阅读了其他几篇文章后,但我很好奇。 JSON.stringify() 似乎适用于其中的一些而不是其他的。此外,结果不一致,在第一轮 positionReferenceType 之后确实得到了字符串化,尽管顺序显然是错误的(再次,我确信这是因为我的递归工作已关闭)。

这个用例有两个方面。首先,我们要删除由系统的一部分生成的原始 JSON 中不必要的“值”键,此时我们无法修改。其次,系统的其他部分使用我们希望从这样的函数输出的离散的较小 JSON 位。输出应该是小的、单独的 JSON 字符串(类似于 HTML 输出中显示的内容)。 输出应该是单个 JSON 字符串,由单独的键/值对组成,如下例所示。

[
    {
        "coordinateReferenceSystem": "26782,15851"
    },
    {
        "positionReferenceType": "geogWgs84"
    },
    {
        "latitude": 0.5050715845821404
    },
    {
        "longitude": -1.604064725846865
    },
    {
        "height": 0
    }
]

我什至还没有接近组装整个 JSON 字符串的地步,因为我只是试图正确地取出配对。

我确定我在这里忽略了一些东西。我应该创建一个对象而不是一个数组来将所有内容都字符串化吗?或者,除了我认为我提到的明显问题之外,它是否在我的递归中绊倒了我?

【问题讨论】:

  • 您正在声明数组,使其仅在 else 子句中初始化。每当你找到一个对象并决定递归时,“arrayJSON”将是undefined
  • 此外,控制台日志记录机制不一定会按照您认为的方式显示数组值。
  • 另外请注意,因为每次在数组中放入东西时都会重新初始化数组,所以最终只会得到一个条目(最多)。
  • 您应该在问题中说明您想要达到的最终结果
  • 我不知道,因为您要达到的目标仍不清楚。

标签: javascript arrays json stringify


【解决方案1】:

一般来说,有两种方法可以递归并得到一个扁平化的数组作为结果。

  • 首先是将结果数组作为参数传递,每次递归都会添加到其中。
  • 其次是每次调用都返回一个数组,上层将其添加到自己的结果中。

无论哪种方式,您都需要先测试 Array 主题,然后再检查 Object 主题,因为 Array 是 Object,通常您会想要为它们做不同的事情。

此外,通常您将在递归之外处理结果(例如,转换为 JSON 然后记录),以保持递归简短。

这是使用第一种方法的实现,其中包括顶级 JSON 转换。 我尽可能地重用了你的变量名。

function propertyTest( currentObject, array, key ) {
   var result = array || [], o;

   if ( Array.isArray( currentObject ) ) {
      currentObject.forEach( function ( e ) { propertyTest( e, result ); } );

   } else if ( typeof ( currentObject ) === 'object' ) {

      if ( 'value' in currentObject && Object.keys( currentObject ).length === 1 ) {
         propertyTest( currentObject.value, result, key );

      } else {

         for ( var property in currentObject ) {
            propertyTest( currentObject[ property ], result, property );
         }

      }

   } else {
      result.push( o = {} );
      o[ key ] = currentObject;
   }

   return array === undefined ? JSON.stringify( result ) : result;
}

var oarsObject = [{
    "coordinateReferenceSystem": "26782,15851",
    "positionReferenceType": "geogWgs84",
    "geogWgs84": {
        "latitude": {
            "value": 0.50507158458214041
        },
        "longitude": {
            "value": -1.604064725846865
        },
        "height": {
            "value": 0.0
        }
    }
}, {
    "coordinateReferenceSystem": "26782,15851",
    "positionReferenceType": "geogWgs84",
    "geogWgs84": {
        "latitude": {
            "value": 0.50509265195620767
        },
        "longitude": {
            "value": -1.5961047836759397
        },
        "height": {
            "value": 0.0
        }
    }
}, {
    "coordinateReferenceSystem": "26782,15851",
    "positionReferenceType": "geogWgs84",
    "geogWgs84": {
        "latitude": {
            "value": 0.4963464715653228
        },
        "longitude": {
            "value": -1.5960947041991222
        },
        "height": {
            "value": 0.0
        }
    }
}, {
    "coordinateReferenceSystem": "26782,15851",
    "positionReferenceType": "geogWgs84",
    "geogWgs84": {
        "latitude": {
            "value": 0.49632551101280209
        },
        "longitude": {
            "value": -1.604015267530267
        },
        "height": {
            "value": 0.0
        }
    }
}];

alert( propertyTest( oarsObject ) );

【讨论】:

    【解决方案2】:

    您可能希望按照 Sheepy 的说明将结果数组的范围限定在递归函数之外。

    当它是一个数组值时使用forEach,当它是一个对象的对象时使用for。这样,您只需处理一个对象的推送,而不必维护数组。

    Example jsFiddle

    var arrayJSON = [];
    
    function propertyTest(currentObject, key) {
    
        if (Array.isArray(currentObject)) {
            currentObject.forEach(propertyTest);
        } else {
            for (var returnKey in currentObject) {
    
                if (typeof currentObject[returnKey] === 'object') {
                    propertyTest(currentObject[returnKey], returnKey);
                } else {
                    var newKey = (returnKey === 'value' && key) ? key : returnKey;
                    var newObj = {};
                    newObj[newKey] = currentObject[returnKey];
                    arrayJSON.push(newObj);
    
                    $('#method1').append( newKey + ' -- ' + currentObject[returnKey] + '<br />');
                }
            }
        }
    }
    
    propertyTest(oarsObject);
    console.log(JSON.stringify(arrayJSON););
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 2021-01-04
      • 2013-05-14
      • 2017-10-22
      • 2013-05-14
      相关资源
      最近更新 更多