Как получить объект JSON внутри объекта, который находится внутри массива JSON - PullRequest
0 голосов
/ 21 сентября 2019

У меня есть JSON-файл дампа чата.Мне нужно извлечь его и распечатать на сайте.Я новичок, поэтому, пожалуйста, помогите мне.

У меня есть дамп-файл JSON моего рабочего пространства.Я хочу извлечь некоторые ключевые детали из него.Я хочу, чтобы real_name находилось внутри объекта user_profile, который находится внутри массива JSON.Как извлечь это.Также, как мне извлечь все значения real_name (я имею в виду, что есть вложенные объекты). PLease, помогите мне в этом.Аякс может быть?

Ответы [ 4 ]

0 голосов
/ 21 сентября 2019
var obj = 
[
    {
        "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
        "type": "message",
        "text": "hey there",
        "source_team": "TN4AF0V5W",
        "team": "TN4AF0V5W",
        "user_profile": {
            "real_name": "marvelmohinish99",
            "team": "TN4AF0V5W"
        }
    },
    {
        "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
        "type": "message",
        "text": "welcome",
        "source_team": "TN4AF0V5W",
        "team": "TN4AF0V5W",
        "user_profile": {
            "real_name": "marvelmohinish99",
            "team": "TN4AF0V5W"
        }
    },
    {
        "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
        "type": "message",
        "text": "Help me",
        "source_team": "TN4AF0V5W",
        "team": "TN4AF0V5W",
        "user_profile": {
            "real_name": "marvelmohinish99",
            "team": "TN4AF0V5W"
        }
    }
];


for (var i = 0; i < obj.length; i++) {
    console.log("Real name" + i + ": " + obj[i].user_profile.real_name);
}
0 голосов
/ 21 сентября 2019

Если я правильно понимаю, вы хотите извлечь список реальных имен.Как вы сказали, вы используете JavaScript.Присвойте массив переменной, скажем, arr;

    var arr = [
    {
        "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
        "type": "message",
        "text": "hey there",
        "source_team": "TN4AF0V5W",
        "team": "TN4AF0V5W",
        "user_profile": {
            "real_name": "marvelmohinish99",
            "team": "TN4AF0V5W"
        }
    },......,
    "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
        "type": "message",
        "text": "Help me",
        "source_team": "TN4AF0V5W",
        "team": "TN4AF0V5W",
        "user_profile": {
            "real_name": "marvelmohinish99",
            "team": "TN4AF0V5W"
        }
    }];

var list_real_name = arr.map((userObj)=>{
  return userObj['user_profile']['real_name'];
})

0 голосов
/ 21 сентября 2019

Если у вас есть JSON в файле (локально) или удаленно,

следующий скрипт будет работать

     <script>
            function fetchJSONFile(path, callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === 4) {
                if (httpRequest.status === 200) {
                    var data = JSON.parse(httpRequest.responseText);
                    if (callback) callback(data);
                }
            }
        };
        httpRequest.open('GET', path);
        httpRequest.send(); 
    }

    // this requests the file and executes a callback with the parsed result once
    //   it is available. You can give URL just in case you are provided with URL.

fetchJSONFile('test.json', function(data){
        // do something with your data
        console.log(data[0].user_profile.real_name);
    });
        </script>

Использование Ajax

<script>
    $(document).ready(function(){
        $.ajax({
    url: 'test.json',
    type: "GET",
    dataType: 'json',
    success: function (data) {
        $.each(data,function(i,data)
        {
          console.log(data.user_profile.real_name);//This will loop 
      //through the result
        });
        console.log(data[0].user_profile.real_name); //Show only first //result
        }

     });
     });

</script>

Незабудьте добавить Jquery перед кодом Ajax

0 голосов
/ 21 сентября 2019

Просто переберите JSON как-то так.(Позаботьтесь о нулевых значениях)

var obj = [
    {
        "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
        "type": "message",
        "text": "hey there",
        "source_team": "TN4AF0V5W",
        "team": "TN4AF0V5W",
        "user_profile": {
            "real_name": "marvelmohinish99",
            "team": "TN4AF0V5W"
        }
    },
    {
        "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
        "type": "message",
        "text": "welcome",
        "source_team": "TN4AF0V5W",
        "team": "TN4AF0V5W",
        "user_profile": {
            "real_name": "marvelmohinish99",
            "team": "TN4AF0V5W"
        }
    },
    {
        "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
        "type": "message",
        "text": "Help me",
        "source_team": "TN4AF0V5W",
        "team": "TN4AF0V5W",
        "user_profile": {
            "real_name": "marvelmohinish99",
            "team": "TN4AF0V5W"
        }
    }
];


for (var i in obj)
{
     var type = obj[i].type;
     var source_team = obj[i].source_team;

     var user_profile = obj[i].user_profile;

     var real_name = user_profile.real_name;


    alert(source_team+" : "+real_name);

}
...