0

I have a JSON like below:

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

I have to create a hashmap as HashMap<String, HashMap<String,String>> such that the outer most key is key for outer hashmap and values in itself will be a json.

In this case there will be total of 3 key, value pair and for first element i.e username there will be two key value pair for value.

How can I check if json has nested json in itself or not. I have to write a generic code which can case it will be independent of key name and all.

I tried below code but it does not help:

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);
        }
    }

Can someone help me with this,

I want to store in hashmap as shown in below image: (first column is key and value is another hashmap as my json)

enter image description here

Abhinav
  • 1,037
  • 6
  • 20
  • 43
  • Have a look at [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/q/11922383/218196) – Felix Kling Sep 08 '16 at 07:01
  • https://en.wikipedia.org/wiki/JSON Your JSON string does not have any examples of JSON strings within itself. I don't understand exactly what you are trying to do, perhaps you could further explain? – Xotic750 Sep 08 '16 at 07:21

2 Answers2

1

You can transverse the structure and use the instanceof Object method to check for nested JSON object.

Example:

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);
Samuel Toh
  • 18,006
  • 3
  • 24
  • 39
0

The following will detect if your JSON has any well formed nested JSON within it.

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">

But I think you may actually be asking how to perform some kind of data transform, from your update. But it honestly is not clear what you want.

Update:

JSON is a string, to transform it to a Javascript object you use JSON.parse

If your object is of a dynamic structure then you will need to walk your object and create the transform that you want. If the structure is static and always like your example then you can write a transorm specific for that structure.

And example of walking your structure and creating the transform.

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">
Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • I want to know that how I can read JSON and store key value pair in a HashMap as shown in image I have added – Abhinav Sep 08 '16 at 08:11