【问题标题】:Access Array and Object inside JSON访问 JSON 中的数组和对象
【发布时间】:2019-02-04 22:51:56
【问题描述】:

我调用了一个返回 XML 的 get API,并且我要转换为 JSON,但是 xml2js 在元素数组中返回 [Object] [Circular] 和 [Array]。 如何查看元素数组中的内容?

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var convert = require('xml-js');
var request = new XMLHttpRequest();
request.open("GET", url, true, username, password);

request.withCredentials = true;

request.send();
request.onreadystatechange=(e)=>{

    var obj = convert.xml2js(request.responseText);

console.log(obj);

这是输出:

{ declaration:
    { attributes: { version: '1.0', encoding: 'UTF-8', standalone: 'yes' } },
   elements:
     [ { type: 'element',
         name: 'model-response-list',
         attributes: [Object],
         elements: [Array] } ] }

【问题讨论】:

  • console.log(obj.elements[0].elements);

标签: node.js xml get xml2js


【解决方案1】:

节点控制台输出默认隐藏深度嵌套的对象/数组。
可以通过以下方式避免这种行为:

  • console.dir 指定 depth 选项
  • 将对象转换为 JSON 字符串
> var obj = { a: { b: { c: { d: {} } } } };

> console.log(obj);
{ a: { b: { c: [Object] } } }

> console.dir(obj, { depth: null }); // null for unlimited recursion
{ a: { b: { c: { d: {} } } } }

> console.log(JSON.stringify, null, 4); // JSON.stringify can also format input with white spaces (in this case - 4)
{
    "a": {
        "b": {
            "c": {
                "d": {}
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多