taking a JSON and transforming it into an Object within HTML

Asked

Viewed 86 times

0

I’m having a problem with the code below, I get a variable( {Devices}} ) a JSON and I try to convert it into an object to get the information of how many devices I have inside it and how many critical alarms I have for a business rule. However, the Json.Parse method does not work or I am unable to implement it correctly, follow the code below:

<!DOCTYPE html>
<html>
<body>

<p id="in" hidden> {{devices}} </p>
<p id="out"></p>    
<p id="out1"></p>
<p id="out2"></p>

<script type="text/javascript">     
    var strJson = document.getElementById("in").innerHTML;
    //var objJson = JSON.parse(document.getElementById("in").innerHTML); //motivo do erro, ele para o funcionamento aqui
    var contDev = 0;
    var contCritical = 0;
    var nObj = 0;
    var tipo = "";

    document.getElementById("out").innerHTML = typeof strJson; //aqui ele me devolve uma string

    function recursive(obj, key1, key2) {
      if (typeof obj !== 'object'){
        tipo = typeof obj;          
        return;
      }       
      Object.keys(obj).forEach(k => { //para cada objeto ele procura uma chave 
        if (k == key1 && k[key1] == "c8y_MQTTDevice") {
            contDev = contDev + 1;
        } 
        else if (k == key2 && k[key].Critical == 1) {
            contCritical = contCritical + 1;
        }
        else {
          if (typeof obj[k] == 'object') { //se for outro objeto, dentro de um, chama recursivamente
            recursive(obj[k], key, newValue);
          }
        }
      });
    }

    recursive(objJson, "type", "c8y_ActiveAlarmsStatus")

    document.getElementById("out1").innerHTML = "Qtde de Devices: " + contDev;
    document.getElementById("out2").innerHTML = tipo + "___";           
</script>


</body>

Json I get from this variable!

{
  "7097240": {
  "additionParents": {
    "references": [],
    "self": {}
  },
  "owner": "service_device-simulator",
  "childDevices": {
    "references": [],
    "self": 
  },
  "com_cumulocity_model_Agent": {},
  "childAssets": {
    "references": [],
    "self": {}
  },
  "creationTime": "2019-10-01T16:44:15.111+02:00",
  "ts_home": {
    "lng": -47.873174,
    "lat": -22.064469
  },
  "c8y_SupportedOperations": [
    "c8y_Configuration",
    "c8y_Position",
    "c8y_Address",
    "c8y_Mobile",
    "c8y_LocationUpdate",
    "c8y_Firmware",
    "c8y_Restart",
    "c8y_Software"
  ],
  "c8y_Position": {
    "lng": -47.87335,
    "alt": 0,
    "accuracy": 10,
    "lat": -22.065523
  },
  "type": "c8y_MQTTDevice",
  "lastUpdated": "2019-10-18T15:39:31.664+02:00",
  "c8y_ActiveAlarmsStatus": {
    "critical": 0
  },
  "c8y_IsDevice": {},
  "childAdditions": {
    "references": [],
    "self": {}
  },
  "name": "GPS_VW-SC_2 #1",
  "assetParents": {
    "references": [],
    "self": {}
  },
  "deviceParents": {
    "references": [],
    "self":{}
  },
  "self":{},
  "id": "7097240"
}
  • But why are you parsing for Json if this is already one? Your question is unclear.

  • So I’d like to turn the string q I’m getting into an object, so I can work on that, actually wanted to know how many I’m getting and what kind.

  • I think your problem is that Json is invalid.

  • Then I checked and the error that gives is as follows: Uncaught Syntaxerror: Unexpected token { in JSON at position 1 at JSON.parse (<Anonymous>) at <Anonymous>:5:21.... However, when you play on a site that checks and organizes this json for me, which is coming as a string, it organizes neatly and complains if you have any more { a or less!

  • If you notice the second self from top to bottom, the {}

  • Opá Leandrade, actually this Json I think is correct, because in this part I got some information, however I found that the error q I am having is that inside the first tag there is a variable {{Devices}} and when I try to manipulate it takes this string and not the json that is played later, I wonder if there is any way to take the contents of this variable to work within my script?

  • But what syntax is this <p id="in" hidden> {{devices}} </p>?? Usa Angular?

  • There’s actually a cloud platform of the company that I work with, and they make this variable available, and within it a part where I can program in HTML, and when I run my program it takes the name of the variable to work with and not its content, therefore, I do not know if when my script runs it does not take the correct information because the variable is too long to arrive or somehow the value of this variable is only displayed after my program is compiled!

Show 3 more comments

1 answer

0

Hi, Lukas.

Tries to replace:

//var objJson = JSON.parse(document.getElementById("in").innerHTML); //motivo do erro, ele para o funcionamento aqui

for:

var objJson = JSON.parse(strJson);

Hug!

  • I have performed this procedure and it simply does not run, I wonder if there is any other way to turn this string into a javascript object\

  • So I think the problem is in the json format that you’re receiving. It may be some key that is not closing, count all '{' if it does not give an even number is because somewhere it is not closing the keys.

  • OK I’ll check, thank you very much for the help! But logic would be right, I’m new with javascript language!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.