简体   繁体   English

使用 Javascript 解析 JSON 文件

[英]Parsing a JSON file using Javascript

I am importing a nested JSON file and would like to be able to display the data extracted from the JSON file as a table.我正在导入一个嵌套的 JSON 文件,并希望能够将从 JSON 文件中提取的数据显示为表格。

How can I go through the different levels of this JSON file and be able to display specific data I need (example I would only like to display the inner most data).我怎样才能通过这个 JSON 文件的不同级别并能够显示我需要的特定数据(例如我只想显示最里面的数据)。

Also, how can I access the children of nodes that have spaces on their key?另外,如何访问键上有空格的节点的子节点?

Here is a sample JSON file:这是一个示例 JSON 文件:

{
    "1234567ABCD123": [{
            "1111": {
                "File 1 Data Goes Here": {
                    "AA": {
                        "Some more data": {
                            "AAAA": [{
                                    "Data List": {
                                        "01": {
                                            "File Name": {
                                                "FN": "Hello"
                                            },
                                            "Author": {
                                                "A1": "John Doe"
                                            }
                                        }
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        }
    ],
    "7654321ABCD321": [{
            "2222": {
                "File 2 Data Goes Here": {
                    "BB": {
                        "Data List": {
                            "File Name": "Hello Again"
                        }
                    }
                }
            }
        }, {
            "3333": {
                "File 3 Data Goes Here": {
                    "CC": {
                        "Data List1": {
                            "File Name": "Hello Again 2"
                        },
                        "Data List2": {
                            "File Name": "Hello Again 3"
                        },
                        "Data List3": {
                            "File Name": "Hello Again 4"
                        }
                    }
                }
            }
        }
    ]
}

And here is my vue method snippet:这是我的 vue 方法片段:

    changeViaUpload(ev) {
      const file = ev.target.files[0];
      const reader = new FileReader();
      var vm = this;

      reader.onload = function(e) {
        vm.msg = "[" + e.target.result + "]";
        vm.show = true;

        vm.parsedJson = JSON.parse(vm.msg);

        console.log(vm.parsedJson);

        vm.parsedJson.forEach(function(item) {
          console.log("Outermost Data: " + item["1234567ABCD123"]);
        });
      };
      reader.readAsText(file);
    }

CodeSanboxLink: https://codesandbox.io/s/vue-quasar-template-enfjp CodeSanboxLink: https ://codesandbox.io/s/vue-quasar-template-enfjp

Thanks!谢谢!

You don't need to create an arbitrary array from your JSON, you can loop over the keys of your object instead.您不需要从 JSON 创建任意数组,而是可以循环遍历对象的键。

Also, if you want to access keys with spaces, you just use array key syntax, here's a deeply nested example:此外,如果您想访问带有空格的键,您只需使用数组键语法,这是一个深度嵌套的示例:

const json = e.target.result
json['1234567ABCD123'][0]['1111']['File 1 Data Goes Here']['AA']['Some more data']['AAAA'][0]['Data List']["01"]['File Name']['FN']

And here's your loop example:这是您的循环示例:

Object.keys(json).forEach((key) => {
  json[key].forEach((el) => {
    Object.keys(el).forEach((inner) => {
      Object.keys(el[inner]).forEach((descriptor) => {
        console.log(el[inner][descriptor])
      })
    })
  })
})

Not sure on vue part but I have created a sample example which can help you understand how to access the children of nodes that have spaces on their key.不确定 vue 部分,但我创建了一个示例示例,它可以帮助您了解如何访问键上有空格的节点的子节点。 Here is the example:这是示例:

 let jsonData={ "1234567ABCD123": [{ "1111": { "File 1 Data Goes Here": { "AA": { "Some more data": { "AAAA": [{ "Data List": { "01": { "File Name": { "FN": "Hello" }, "Author": { "A1": "John Doe" } } } } ] } } } } } ], "7654321ABCD321": [{ "2222": { "File 2 Data Goes Here": { "BB": { "Data List": { "File Name": "Hello Again" } } } } }, { "3333": { "File 3 Data Goes Here": { "CC": { "Data List1": { "File Name": "Hello Again 2" }, "Data List2": { "File Name": "Hello Again 3" }, "Data List3": { "File Name": "Hello Again 4" } } } } } ] } console.log(jsonData['1234567ABCD123'][0]['1111']['File 1 Data Goes Here']['AA']['Some more data']['AAAA'][0]['Data List']['01']['File Name'])

We can access Objects property through two methods:我们可以通过两种方法访问 Objects 属性:

1) Dot notation :- property identifies can only be alphanumeric (and _ and $). 1)点符号:- 属性标识只能是字母数字(和 _ 和 $)。 Properties can't start with a number.属性不能以数字开头。

2) Square bracket :- Square bracket notation allows access to properties containing special characters and selection of properties using variables 2)方括号:- 方括号表示法允许访问包含特殊字符的属性和使用变量选择属性

You can found more about them here .您可以在此处找到有关它们的更多信息。

I'm not exactly sure what the problem is, but if you need help to loop through a JSON and extract all of the data, say, two levels down, into a new JSON, then you can use the for...in to loop through a JSON, or do Object.entries(json).forEach , then store the result 2 layers down in a new JSON.我不太确定问题是什么,但是如果您需要帮助来遍历 JSON 并将所有数据(例如向下两级)提取到新的 JSON 中,那么您可以使用for...in循环遍历 JSON,或执行Object.entries(json).forEach ,然后将结果存储在新的 JSON 中 2 层。

For example, if you want to extract all of the data 2 layers down and put it in a new JSON, do something like the following (assuming the parsed json is in a variable called "parsed"):例如,如果您想提取 2 层的所有数据并将其放入新的 JSON 中,请执行以下操作(假设解析后的 json 位于名为“已解析”的变量中):

 var parsed = { "1234567ABCD123": [{ "1111": { "File 1 Data Goes Here": { "AA": { "Some more data": { "AAAA": [{ "Data List": { "01": { "File Name": { "FN": "Hello" }, "Author": { "A1": "John Doe" } } } } ] } } } } } ], "7654321ABCD321": [{ "2222": { "File 2 Data Goes Here": { "BB": { "Data List": { "File Name": "Hello Again" } } } } }, { "3333": { "File 3 Data Goes Here": { "CC": { "Data List1": { "File Name": "Hello Again 2" }, "Data List2": { "File Name": "Hello Again 3" }, "Data List3": { "File Name": "Hello Again 4" } } } } } ] }, newP = {}; for(var k in parsed) { if(parsed[k].forEach) { parsed[k].forEach(x => { for(var kk in x) { for(var okk in x[kk]) { newP[okk] = x[kk][okk]; } } }); } } console.log("And your 2nd level data is: ", newP);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM