Error with loadJSON method
See original GitHub issueOS: MacOS 11.6 Node: 15.11.0 Minisearch 3.1.0
====================================
Building index with the following code:
const miniSearch = require('minisearch')
const fs = require('fs');
const path = require("path");
const getProductFiles = function(dirPath, arrayOfFiles) {
files = fs.readdirSync(dirPath);
arrayOfFiles = arrayOfFiles || [];
files.forEach(function(file) {
let fn = path.join(dirPath, file);
(fs.statSync(fn).isDirectory()) ?
arrayOfFiles = getProductFiles(fn, arrayOfFiles) :
arrayOfFiles.push(path.join(dirPath, "/", file));
});
return arrayOfFiles;
}
let arrayOfFiles;
const inputFiles =
getProductFiles(path.join('src', '_data'), arrayOfFiles)
.filter(file => path.extname(file) === '.json');
let idCounter = 0
let ms = new miniSearch({
fields: [ 'sku', 'category', 'type', 'subtype', 'name', 'description', 'cost',
'mass', 'size', 'techLevel', 'qrebs', 'tags' ],
storeFields: ['sku', 'name', 'description', 'cost']
});
inputFiles.forEach(file => {
// get the products from the file
let products = JSON.parse(fs.readFileSync(`${file}`));
// build search index object and add to search index
products.forEach(product => {
product.id = idCounter++;
ms.add(product);
})
})
fs.writeFileSync('src/_data/searchindex.idx', JSON.stringify(ms))
let jsonIdx = fs.readFileSync('src/_data/searchindex.idx', 'utf8');
let ms2 = new miniSearch.loadJSON(jsonIdx, {
fields: [ 'sku', 'category', 'type', 'subtype', 'name', 'description', 'cost',
'mass', 'size', 'techLevel', 'qrebs', 'tags' ],
storeFields: ['sku', 'name', 'description', 'cost']
});
// console.log(`ms is ${(Array.isArray(ms)) ? "" : "not"})`)
let searchTerm = 'portal'
let options = (searchTerm.includes(' and ')) ? { combineWith: 'AND'} : {}
let res = ms2.search(searchTerm, options);
res.forEach(result => console.log(result));
The code above appears to work correctly and returns search results (use attached file searchindex.idx)
In the code below, I may be doing something wrong with the fetch, but I’m not sure what it is.
fetch(searchIndexLocation)
.then((res) => res.json())
.then((data) => {
console.log(data);
const jsonDocs = data;
// line 272 is the next line
let miniSearch = new MiniSearch.loadJSON(jsonDocs, {
fields: [ 'sku', 'category', 'type', 'subtype', 'name', 'description', 'cost',
'mass', 'size', 'techLevel', 'qrebs', 'tags' ],
storeFields: ['sku', 'name', 'description', 'cost']
});
})
.catch((err) => console.log(err));
because I am consistently getting the following error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at new t.loadJSON (index.js:1126)
at scripts.js:272
I’m still a bit new to the fetch API but it looks like something is occurring with the index file before it is getting to the loadJSON call.
Any clues appreciated. : searchindex.idx.zip -/
Issue Analytics
- State:
- Created 2 years ago
- Comments:14 (4 by maintainers)
Top Results From Across the Web
loadJSON() function error message - Coding Questions
I'm a newbie to p5.js but I've been playing around with using API's. Whenever I call an API using the function loadJSON(), no...
Read more >Load JSON file, error undefined - Stack Overflow
I'm trying to load a JSON file that I'll use as constants file, but I'm always getting the error undefined, could any one...
Read more >reference | loadJSON() - P5.js
Note that even if the JSON file contains an Array, an Object will be returned with index numbers as keys. This method is...
Read more >p5.js | loadJSON() Function - GeeksforGeeks
The first argument for this function is the error response. It is an optional parameter. Return Value: It returns an object with the...
Read more >json_decode - Manual - PHP
This function only works with UTF-8 encoded strings. ... while previously, an error of level E_WARNING was raised. ... function loadJSON($Obj, $json)
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I think I found the issue:
loadJSON
expects a JSON string, but you’re already converting the fetch response to a JS object withres.json()
. So I think you just need to useres.text()
there instead. (You could also useMiniSearch.loadJS
with the JS object, which is whatloadJSON
calls internally, but that’s undocumented API and therefore not a good idea.)I didn’t try it with the Fetch API, but loading works fine for me with this quick and dirty XHR example:
You are absolutely right @JustAnotherArchivist .
I am closing the issue as it should be solved, but feel free to comment further if necessary.