Recursively list all object property paths from JS

2019-02-16 03:04发布

问题:

This question already has an answer here:

  • Find by key deep in a nested object 7 answers

I have to fight with JSON returns (which i get out of a XML response from Amazon Marketplace API). It contains arrays, subarrays and so on. At the moment i need to get only 2 values (AmazonOrderId and OrderItem object), but i don't find a way to address them directly. I still try for hours. Recursive things scare me a bit.

There are so many tools out there, also for beatifying or editing JSON. So is there possibly also a solution which shows all the property links recursively? Up to now i have not found something like this.

UPDATE: With the code from squint's answer i have build a quick and dirty tool which does what i wanted. Here it is: http://output.jsbin.com/gunixo

like:

myJSON.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].QuantityOrdered
myJSON.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].Title
...

This would really save time, in such a case.

    {
    "ListOrderItemsResponse": {
        "$": {
            "xmlns": "https://mws.amazonservices.com/Orders/2013-09-01"
        },
        "ListOrderItemsResult": [{
            "OrderItems": [{
                "OrderItem": [{
                    "QuantityOrdered": ["1"],
                    "Title": ["My Product Title"],
                    "ShippingTax": [{
                        "CurrencyCode": ["EUR"],
                        "Amount": ["0.00"]
                    }],
                    "PromotionDiscount": [{
                        "CurrencyCode": ["EUR"],
                        "Amount": ["0.00"]
                    }],
                    "ConditionId": ["New"],
                    "ASIN": ["BXXXI5W6M8"],
                    "SellerSKU": ["KNDR-BTTWSCH-BGSBNNY"],
                    "OrderItemId": ["67050234000659"],
                    "GiftWrapTax": [{
                        "CurrencyCode": ["EUR"],
                        "Amount": ["0.00"]
                    }],
                    "QuantityShipped": ["1"],
                    "ShippingPrice": [{
                        "CurrencyCode": ["EUR"],
                        "Amount": ["4.90"]
                    }],
                    "GiftWrapPrice": [{
                        "CurrencyCode": ["EUR"],
                        "Amount": ["0.00"]
                    }],
                    "ConditionSubtypeId": ["New"],
                    "ItemPrice": [{
                        "CurrencyCode": ["EUR"],
                        "Amount": ["15.77"]
                    }],
                    "ItemTax": [{
                        "CurrencyCode": ["EUR"],
                        "Amount": ["0.00"]
                    }],
                    "ShippingDiscount": [{
                        "CurrencyCode": ["EUR"],
                        "Amount": ["0.00"]
                    }]
                }]
            }],
            "AmazonOrderId": ["304-6107803-0000000"]
        }],
        "ResponseMetadata": [{
            "RequestId": ["dd64dd40-d939-4ea1-875d-xxxxxxxxxxxx"]
        }]
    }
}

回答1:

If you truly only need those two values, you can do it while it's being parsed.

var data = {};

// ----------v--- Original JSON data before parsing.
JSON.parse(myJSON, function(k, v) {
    if (k === "AmazonOrderId" || k === "OrderItem") {
        data[k] = v;
    }
    return v;
});

That said... recursive stuff shouldn't be scary. And there are many pre-written functions on StackOverflow that accept the property you're looking for and return the value, so you could just use one of those.


Here's a simple recursive function that generates paths to all the data.

function objectToPaths(data) {
  var validId = /^[a-z_$][a-z0-9_$]*$/i;
  var result = [];
  doIt(data, "");
  return result;

  function doIt(data, s) {
    if (data && typeof data === "object") {
      if (Array.isArray(data)) {
        for (var i = 0; i < data.length; i++) {
          doIt(data[i], s + "[" + i + "]");
        }
      } else {
        for (var p in data) {
          if (validId.test(p)) {
            doIt(data[p], s + "." + p);
          } else {
            doIt(data[p], s + "[\"" + p + "\"]");
          }
        }
      }
    } else {
      result.push(s);
    }
  }
}

All Array members are listed individually. This could be consolidated if you know that the data structures in those array members are always identical.

Result for your data:

.ListOrderItemsResponse.$.xmlns
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].QuantityOrdered[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].Title[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ShippingTax[0].CurrencyCode[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ShippingTax[0].Amount[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].PromotionDiscount[0].CurrencyCode[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].PromotionDiscount[0].Amount[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ConditionId[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ASIN[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].SellerSKU[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].OrderItemId[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].GiftWrapTax[0].CurrencyCode[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].GiftWrapTax[0].Amount[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].QuantityShipped[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ShippingPrice[0].CurrencyCode[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ShippingPrice[0].Amount[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].GiftWrapPrice[0].CurrencyCode[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].GiftWrapPrice[0].Amount[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ConditionSubtypeId[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ItemPrice[0].CurrencyCode[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ItemPrice[0].Amount[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ItemTax[0].CurrencyCode[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ItemTax[0].Amount[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ShippingDiscount[0].CurrencyCode[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].OrderItems[0].OrderItem[0].ShippingDiscount[0].Amount[0]
.ListOrderItemsResponse.ListOrderItemsResult[0].AmazonOrderId[0]
.ListOrderItemsResponse.ResponseMetadata[0].RequestId[0]