gpt4 book ai didi

javascript - 如何解析本地存储的大型 json 外部文件(~30 MB)以填充选择下拉列表以避免加载时间过长?

转载 作者:太空宇宙 更新时间:2023-11-03 20:24:53 24 4
gpt4 key购买 nike

我正在尝试解析一个包含大约 209,579 个对象(~30MB 文件大小)的 JSON 文件,并使用选择选项标签在下拉菜单中填充这些对象(名称和值属性)。我可以使用 jquery getJSON 方法解析整个文件,以使用针对 DOM 元素的传统方式解析和填充它,但是当我选择下拉菜单时,显示内容所需的时间太长,并且会在该时间段内禁用浏览器.

我曾尝试使用包含约 100 个对象(明显更少)的较小数据集,并且页面呈现下拉列表的速度很快且不会滞后。这就是为什么我认为我因为我的大型 JSON 对象数据集而遇到问题的原因。

<!--html code-->
<h3>Select your Location:</h3>
<select id="locality-dropdown" name="locality">
</select>

//referenced from https://www.codebyamir.com/blog/populate-a-select-dropdown-list-with-json
//(I have used the same technique)

let dropdown = document.getElementById('locality-dropdown');
dropdown.length = 0;

let defaultOption = document.createElement('option');
defaultOption.text = 'Choose State/Province';

dropdown.add(defaultOption);
dropdown.selectedIndex = 0;

const url = 'js/city_list1.json';

fetch(url)
.then(
function(response) {
if (response.status !== 200) {
console.warn('Looks like there was a problem. Status Code: ' +
response.status);
return;
}

// Examine the text in the response
response.json().then(function(data) {
let option;

for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].name;
option.value = data[i].id;
dropdown.add(option);
}
});
}
)
.catch(function(err) {
console.error('Fetch Error -', err);
});

我希望像在普通网站中一样呈现下拉菜单,但就我而言,当我单击下拉菜单时,浏览器停止响应并需要一段时间才能加载下拉菜单中的内容。

最佳答案

正如您正确指出的那样,您的案例中的瓶颈是您试图一次加载整个数据集。您应该考虑改为在页面( block )中加载该数据,并且可能有一个窗口组件仅加载/呈现当前显示的数据。

正如其他人指出的那样,JSON 不是存储庞大数据集的最佳格式,数据库要好得多,即使是像 SQLite 这样简单和小的格式。会做的。

但是,如果您仍然更愿意继续使用 JSON,我建议您尝试使用允许您解析部分 JSON block 的库之一,并在某种程度上模仿您使用数据库时的情况和数据的分页加载。

stream-json为例(NodeJS 模块,但我想人们可以很容易地找到适用于每种后端技术的类似东西)。

stream-json is a micro-library of node.js stream components with minimal dependencies for creating custom data processors oriented on processing huge JSON files while requiring a minimal memory footprint. It can parse JSON files far exceeding available memory. Even individual primitive data items (keys, strings, and numbers) can be streamed piece-wise.

const { chain } = require('stream-chain')

const { parser } = require('stream-json')
const { pick } = require('stream-json/filters/Pick')
const { streamValues } = require('stream-json/streamers/StreamValues')

const fs = require('fs')

const pipeline = chain([
fs.createReadStream('sample.json'),
parser(),
pick({ filter: 'data' }),
streamValues(),
data => {
const value = data.value
return value && value.department === 'accounting' ? data : null
}
])

let counter = 0
pipeline.on('data', () => ++counter)
pipeline.on('end', () =>
console.log(`The accounting department has ${counter} employees.`)
)

关于javascript - 如何解析本地存储的大型 json 外部文件(~30 MB)以填充选择下拉列表以避免加载时间过长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58776035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com