更简单的方法:
第一个函数查找所有属性及其级别
function findAllProperties(obj)
{
var retVal = [];
(function findProperty(obj, depth)
{
for (var prop in obj)
{
if (obj[prop] instanceof Object)
{
findProperty(obj[prop], depth + 1);
}
else
{
retVal.push({"name" : prop, "depth" : depth});
}
}
})(obj, 0);
return retVal;
}
第二个函数查找具有最高级别的属性
function siftInnerMost(items)
{
var maxDepth = 0, retVal = [];
for (var i in items)
{
if (items[i].depth == maxDepth)
{
retVal.push(items[i].name);
}
else if (items[i].depth > maxDepth)
{
maxDepth = items[i].depth;
retVal = [items[i].name];
}
}
return retVal;
}
现在你可以找到inner most
钥匙
var inners = findAllProperties(data);
var innerMost = siftInnerMost(inners);
JSFiddle 演示
带有Json-Simple库 的Java解决方案
public class InnerMostFinder
{
private List<Pair> inners = new ArrayList<Pair>();
private static class Pair
{
int level;
String property;
public Pair(int level, String property)
{
this.level = level;
this.property = property;
}
}
private void findAllProperties(final JSONObject obj, final int level)
{
for (Object key : obj.keySet())
{
Object innerObj = obj.get(key);
if (innerObj instanceof JSONObject)
{
findAllProperties((JSONObject) innerObj, level + 1);
}
else
{
inners.add(new Pair(level, (String) key));
}
}
}
public List<String> getInnerMost(final JSONObject obj)
{
final List<String> retVal = new ArrayList<String>();
int maxLevel = 0;
findAllProperties(obj, maxLevel);
for (final Pair pair : inners)
{
if (pair.level == maxLevel)
{
retVal.add(pair.property);
}
else if (pair.level > maxLevel)
{
maxLevel = pair.level;
retVal.clear();
retVal.add(pair.property);
}
}
return retVal;
}
}
用法
JSONObject obj = (JSONObject) new JSONParser()
.parse(new FileReader(new File("D:/test.json")));
System.out.println(new InnerMostFinder().getInnerMost(obj));