saminathan saminathan - 29 days ago 5
Javascript Question

How to get the key and pair value from json if the pair value as string

Below is my json response

"head": null,
"body": {
"8431073": "CN0028-00"
"responseTime": null,
"leftPanel": null

I like to get the key and value from body. Below is my ajax call where i would like to take the key and value. but its returning empty value.


url: "ulhcircuit.json",
method: "GET",
contentType: "application/json; charset=utf-8",
success: function(data) {
result = data.body;
fail: function(xhr, ajaxOptions, thrownError) {

function gethtmlvalues(result) {
var circuitList = result;
var cktInstId = "";
var cktName = "";
if (circuitList != null) {

if (circuitList.length > 0) {
$.each(circuitList, function(key, value) {

cktInstId = key; // returns empty values
cktName = value; // returns empty values

I would like to have the cktInstId as 8431073 and cktName as CN0028-00

Please help me.Thanks in advance


When your response enters gethtmlvalues, you are passing data.body, which based on the JSON you've given looks like:

{ "8431073": "CN0028-00" }

This is a plain JS object, not a list, and existence of a length property doesn't mean amount of items it contains. This means you don't need the length check (you are comparing undefined > 0). You also don't need a (wrongly) named extra variable circuitList, you can just use result.

function gethtmlvalues(result){
  if(result != null){    
      $.each(result,function(key, value){
          console.log(key, value); // this will print your key value pair