Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append JSON to div

I am new to web development and I am having hard time appending JSON to div so that the value is displayed on the webpage. I have checked other questions but most of the responses are associated with PHP which is not my case. Can anyone help me figure out what I am missing that is not letting the JSON value not to be displayed on a webpage. Here is some part of the JSON file content:

{ "array": [
   "firstArray": {
    "firstKey": "firstValue",
    "secondKey": "secondValue"
   },
   "secondArray":{
    "firstKey": "firstValue",
    "secondKey": "secondValue"
   }
  ]     
}

Here is part of JavaScript that I am expecting to display the value which is found under first array and first key of the above JSON

function print(data){   // lets assume data represents the whole JSON data
var newDiv = $("<div />", {'id': 'new'})
newDiv.append($("<span />", data.array[0].firstArray.firstKey}))
}

I am very new to web development and I am very interested to learn so please help me as much as possible.


1 Answers

Try the following:

var data = { "array": [
   {"firstArray":{
    "firstKey": "firstValue",
    "secondKey": "secondValue"
   }},
   {"secondArray":{
    "firstKey": "firstValue",
    "secondKey": "secondValue"
   }}
  ]     
};

function print(data){  
    $('body').append($("<div id='new'/>"));
    $('body').append($("<div id='new2'/>"));

    $('#new').append($("<span>"+data.array[0].firstArray.firstKey+"   "+"</span>"));
    $('#new').append($("<span>"+data.array[0].firstArray.secondKey+"</span>"));

    $('#new2').append($("<span>"+data.array[1].secondArray.firstKey+"   "+"</span>"));
    $('#new2').append($("<span>"+data.array[1].secondArray.secondKey+"</span>"));
}

print(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 156
Mamun Avatar answered Feb 25 '26 01:02

Mamun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!