Выбор узлов JSON из сильно вложенного внешнего файла - PullRequest
0 голосов
/ 18 января 2019

Я работаю с локальным файлом JSON и пытаюсь отрисовать определенные узлы из него. Однако причина, по которой я спрашиваю об этом в StackOverflow, заключается в том, что сам файл json сильно вложен в тонну дочерних узлов, и я не знаю, как пройти файл json, подобный этому. Я сплющил данные, пытаясь смягчить проблему, но, похоже, это не принесло пользы.

Я пытаюсь получить доступ к __text специально (т.е. __text": "Guides & Protocols")

Вот пример данных:

{
    "feed": {
        "id": "[redacted]",
        "title": "",
        "updated": "2019-01-17T21:01:03Z",
        "entry": [
            {
                "id": "Web/Lists(guid'[redacted]')/Items(1)",
                "category": {
                    "_term": "[redacted]",
                    "_scheme": "[redacted url]"
                },
                "link": {
                    "_rel": "edit",
                    "_href": "Web/Lists(guid'[redacted]')/Items(1)"
                },
                "title": "",
                "updated": "2019-01-17T21:01:03Z",
                "author": {
                    "name": ""
                },
                "content": {
                    "properties": {
                        "ResourceType": {
                            "element": {
                                "Label": {
                                    "__prefix": "d",
                                    "__text": "Guides & Protocols" <--------------------
                                },
                                "TermGuid": {
                                    "__prefix": "d",
                                    "__text": "[redacted]"
                                },
                                "WssId": {
                                    "_m:type": "[redacted]",
                                    "__prefix": "d",
                                    "__text": "706"
                                },
                                "__prefix": "d"
                            },
                            "_m:type": "Collection([redacted])",
                            "__prefix": "d"
                        },
                        "__prefix": "m"
                    },
                    "_type": "application/xml"
                },
                "_m:etag": "\"2\""
            }
         ...
     ]
 }

JavaScript:

import $ from 'jquery';
import axios from 'axios';

import myJSONfile from '../../../public/myJSONfile.json';
import tinyJsonFlat from '../../../public/tinyJsonFlat.json'; // Top 10, ResourceTypes only

import { basename } from 'path';


    export default class {
        constructor() {
            $('<div class="test-div">testing</div>').appendTo(document.body);

            this.loadData();
        }


        loadData() {
            var data = tinyJsonFlat // syntax seems off

            var result = $.map(data.data, function(obj) {
                return obj.Label + obj.__text

                $(document.body).append(result);
                console.log(result);
                // $('#site-labels').text(JSON.stringify(tinyJsonFlat)); /// earlier solution
            });

        }

    }

Ответы [ 2 ]

0 голосов
/ 18 января 2019

Попробуйте:

Array.prototype.findKey = function(key){

  let res = [];

  function traverseChildren(input, lookFor) {
    //By default, imagine what we are looking at is JSON...
    let children = Object.keys(input);
    //... however, if it is an array, just stick with that.
    if (Array.isArray(input)){
      children = input;
    }
    //Go through everything in the target
    for (i = 0; i < children.length; i++) {
      //Have we found the *key* we are looking for?
      if (children[i] === lookFor && Array.isArray(input)) {
        //If so, record the value.
        res.push(input[lookFor]);
      } else {
        //If not, keep searching.
        traverseChildren(input[children[i]]);
      }
    }
  }

  traverseChildren(this, key);
  return res;
}
0 голосов
/ 18 января 2019

Когда вы анализируете файл JSON, он ведет себя так же, как обычный объект Javascript, тогда:

myJSONfile.feed.entry[index].content.properties.ResourceType.element.Label.__text

Обратите внимание на индекс записи, к которой вы получаете доступ:

myJSONfile.feed.entry[index]

const json = {
  "feed": {
    "id": "[redacted]",
    "title": "",
    "updated": "2019-01-17T21:01:03Z",
    "entry": [
      {
        "id": "Web/Lists(guid'[redacted]')/Items(1)",
        "category": {
          "_term": "[redacted]",
          "_scheme": "[redacted url]"
        },
        "link": {
          "_rel": "edit",
          "_href": "Web/Lists(guid'[redacted]')/Items(1)"
        },
        "title": "",
        "updated": "2019-01-17T21:01:03Z",
        "author": {
          "name": ""
        },
        "content": {
          "properties": {
            "ResourceType": {
              "element": {
                "Label": {
                  "__prefix": "d",
                  "__text": "Guides & Protocols"
                },
                "TermGuid": {
                  "__prefix": "d",
                  "__text": "[redacted]"
                },
                "WssId": {
                  "_m:type": "[redacted]",
                  "__prefix": "d",
                  "__text": "706"
                },
                "__prefix": "d"
              },
              "_m:type": "Collection([redacted])",
              "__prefix": "d"
            },
            "__prefix": "m"
          },
          "_type": "application/xml"
        },
        "_m:etag": "\"2\""
      }
    ]
  }
}
   
console.log(json.feed.entry[0].content.properties.ResourceType.element.Label.__text)
// Guides & Protocols
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...