Nodejs:读取嵌套的json独立

时间:2016-09-08 06:58:01

标签: javascript json node.js

我有一个JSON如下:

{
    "username": {
        "A1": {
            "L1": "usernameL1",
            "V1": "usernameV1"
        },
        "A2": {
            "L2": "usernameL2",
            "V2": "usernameV2"
        }
    },
    "password": {
        "L": "passwordL",
        "V": "passwordV"
    },
    "loginButton": {
        "L": "loginButtonL",
        "V": "loginButtonV"
    }
}

我必须创建一个哈希映射为HashMap<String, HashMap<String,String>>,这样最外面的键是外部hashmap的键,值本身就是一个json。

在这种情况下,总共有3 keyvalue对,对于第一个元素,即用户名,将有两个键值对值。

如何检查json是否嵌套了json。我必须编写一个通用代码,它可以独立于key名称和所有。

我尝试了以下代码,但没有帮助:

jsonHierarchy = JSON.parse(data);
        for(var json in jsonHierarchy){
        j = jsonHierarchy[json]
        for(var k in j){
            console.log(k)
            var sub_key = k;
            var sub_val = json[k];
            console.log("   Key: "+sub_key+" Value: "+sub_val);
        }
    }

有人可以帮我解决这个问题,

我想存储在hashmap中,如下图所示:(第一列是键,值是另一个hashmap作为我的json)

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以横向结构并使用instanceof Object方法检查嵌套的JSON对象。

示例:

&#13;
&#13;
var data =
{
  "username": {
    "A1": {
      "L1": "usernameL1",
      "V1": "usernameV1"
    },
    "A2": {
      "L2": "usernameL2",
      "V2": "usernameV2"
    }
  } ,
  "password": {
    "L": "passwordL",
    "V": "passwordV"
  },
  "loginButton": {
    "L": "loginButtonL",
    "V": "loginButtonV"
  }
};

function walk(root) {
  for (var property in root) {
    // Extend this if-else clause to check for other things like Array.
    if (root[property] instanceof Array)
      root[property].forEach(item => { walk(item); });
    // If has nested JSON object
    else if (root[property] instanceof Object) {
      console.log("Propery: " + property + ", has nested JSON");
      walk(root[property]);
    }
  }
}

walk(data);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

以下内容将检测您的JSON中是否包含任何格式良好的嵌套JSON。

const walk = returnExports;

function hasNestedJSON(obj) {
  let found = false;
  walk(javascriptObject, Object.keys, function(value, prop, object, depth) {
    if (typeof value === 'string') {
      try {
        JSON.parse(value);
        found = true;
        return walk.BREAK;
      } catch (e) {}
    }
  });
  return found;
}

const jsonString = '{"username":{"A1":{"L1":"usernameL1","V1":"usernameV1"},"A2":{"L2":"usernameL2","V2":"usernameV2"}},"password":{"L":"passwordL","V":"passwordV"},"loginButton":{"L":"loginButtonL","V":"loginButtonV"}}';
const javascriptObject = JSON.parse(jsonString);
const result = hasNestedJSON(javascriptObject);
document.getElementById('out').textContent = result;
console.log(result);
<script src="https://rawgithub.com/Xotic750/object-walk-x/master/lib/object-walk-x.js"></script>
<pre id="out">

但我认为您实际上可能会询问如何从您的更新中执行某种数据转换。但老实说,不清楚你想要什么。

更新

JSON是一个字符串,可将其转换为您使用的Javascript对象JSON.parse

如果您的对象是动态结构,那么您将需要遍历对象并创建所需的变换。如果结构是静态的并且总是像您的示例那么您可以编写特定于该结构的变换。

走你的结构并创建变换的例子。

const walk = returnExports;
const jsonString = '{"username":{"A1":{"L1":"usernameL1","V1":"usernameV1"},"A2":{"L2":"usernameL2","V2":"usernameV2"}},"password":{"L":"passwordL","V":"passwordV"},"loginButton":{"L":"loginButtonL","V":"loginButtonV"}}';
const javascriptObject = JSON.parse(jsonString);
const transformed = {};
let currentArray;
let currentProp;
let lastProp;
let lastDepth;
walk(javascriptObject, Object.keys, function(value, prop, object, depth) {
  if (depth === 1 && !transformed[prop]) {
    transformed[prop] = [];
    currentProp = prop;
  }
  if (depth > 1) {
    if (lastProp !== prop && lastDepth !== depth) {
      transformed[currentProp].push([]);
    }
    lastProp = prop;
    lastDepth = depth;
  }
  currentArray = transformed[currentProp].pop() || [];
  if (typeof value === 'string') {
    currentArray.push(value);
  }
  if (currentArray.length) {
    transformed[currentProp].push(currentArray);
  }
});
console.log(transformed);
<script src="https://rawgithub.com/Xotic750/object-walk-x/master/lib/object-walk-x.js"></script>
<pre id="out">