Perhaps a simple question but I am still new to JS / nodeJS.
I have a script that is doing some basic string matching (dict.js), and I am trying to access a JSON formatted object from another file (words.json) to iterate through.
The directory structure looks like:
scratch
- algorithms
- dict.js
- utilities
- words.json
The contents of the files are:
words.json
{"a": 1,"aa": 1,"aaa": 1,"aah": 1,"aahed": 1,"aahing": 1,"aahs": 1,"aal": 1}
dict.js
decode (password) {
const jsonData = require('../utilities/words.json');
myObj = JSON.parse(jsonData);
for (const x in myObj) {
console.log(x)
// compare password against item in words.json
}
console.log(Object.keys(myObj).length)
return "stub";
}
I am getting an error in developer tools when I create a block (this is the backend to a block in Scratch) that uses this Decode function.
Uncaught SyntaxError: Unexpected token o in JSON at position 1
Thanks
In nodejs environment you can directly import json file data without parsing it. For exaple:
const myObj = require('../utilities/words');
This gives you the data in your json file as a ready-to-go object.
In your case, you are trying to parse json object with JSON.parse() which expects stringified json. So just remove the part JSON.parse(jsonData);
Related
I'm trying to pass python dictionaries and javascript objects back and forth as necessary. From similar questions, I've gathered that I need to do this.
Python:
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
Javascript:
var jsonPosts = JSON.parse({{ posts }});
console.log(jsonPosts);
Likewise, these doesn't work either:
var jsonPosts = JSON.parse(posts|tojson);
var jsonPosts = {{ posts|tojson }};
The JS error I'm triggering is TypeError: Object of type Undefined is not JSON serializable
I got this advice from the following Q/A:
Python to Javascript JSON objects (Flask)
How can I pass data from Flask to JavaScript in a template?
How can I fix this?
Edit:
I've used answer recommendation and found the following error to be present in the console:
VM129:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at about:16
Corresponding to
let jsonPosts = JSON.parse();
It seems that it doesn't have access to encoded_posts.
You need to use the encoded posts:
encoded_posts = json.dumps(posts)
That will give you string, which is what JSON.parse is expecting.
var jsonPosts = JSON.parse({{ encoded_posts }});
I have a JSON that looks like this:
{"marker":[{"#attributes":{"start":"Im Berge",
"finish":"Eichelberger Stra\u00dfe"
...
I am trying to parse the attributes inside the "#attributes", but have not found a way to do it. What I tried so far:
const fs = require('fs');
var jsonObj = JSON.parse(fs.readFileSync('route1.json', 'utf8'));
console.log(jsonObj['#attributes']);
Also tried the same with
console.log(jsonObj.marker['#attributes']);
Neither of which work. I understand that this is supposed to be a json-ld and that I'm supposed to parse an object with an "#" sign with ['#attributes'], but either way I always get an error or undefined. I got the JSON from an API I wanna use and it is in there multiple times, so I have no way around it.
.marker is an array so:
console.log(jsonObj.marker[0]['#attributes']);
But you may want to loop through it:
jsonObj.marker.forEach(marker => console.log(marker['#attributes']));
You can require a JSON file, instead of JSON.parse & fs.readFileSync
var jsonObj = require('./route1.json');
This question is NativeScript related.
I want to process the binary data after being read from file.
I followed the official doc here:
file-system#readingwriting-binary-data-fromto-a-file
with this, I can successfully read and write (in other word: "copy") the binary files. What I'm trying to accomplish now is to process the binary data ( it could be any sort of binary data, eg. image, database, etc... ) and then save it in file. But I can't figure out how to retrieve the raw binary data from a variable object returned by readSync, please have a look at the code below (btw currently testing on ios environment):
var source = sourceFile.readSync(e=> { error = e; });
console.log(typeof source.bytes);
console.log(typeof source.length);
console.log(source.bytes);
console.log(source.length);
When I execute this code, I see the these messages in console log:
CONSOLE LOG file:///app/views/login/login.js:99:12: object
CONSOLE LOG file:///app/views/login/login.js:100:12: number
CONSOLE LOG file:///app/views/login/login.js:101:12: <Pointer: 0x11da02000>
CONSOLE LOG file:///app/views/login/login.js:102:12: 1720728
From this output I surmise that source.bytes is a pointer object and not an array object... My question is: is there a way to store the data into array, possibily in Uint8Array type?
I finally found a solution to make it work on ios environment. It was written in the source code:
NativeScript: objc!Foundation.d.ts
So, use getBytes() to retrieve the data into array abject.
Example code:
var arr = new ArrayBuffer(source.length);
source.getBytes(arr);
var uint8arr = new Uint8Array(arr);
When I try to print my object it gives me no response.
var steaminv = JSON.parse("http://steamcommunity.com/id/pootel/inventory/json/730/2.json");
document.write(steaminv);
You should request the file first and then parse the content of the file.
JSON.parse requires a json object encoded as string. It does not request the file for you.
If you are using node, you can use request module. If you are using javascript on browser, you can use jQuery and do an ajax call to get the content of the file.
Please take a look at this question: How do I receive a JSON file using AJAX and parse it using javascript?
Just to give you an idea what JSON.parse does:
var str = '{"name":"Amir","age":25}';
var obj = JSON.parse(str);
console.log(obj.name);
console.log(obj.age);
I'm retrieving data from MongoDB and then sending it to client:
var bsonDocument = ... retrieve from database ...
var dto = new Dto { MyBson = bsonDocument.ToJson() };
On the client I'm trying to parse MyBson property using JSON.parse.
I'm getting the following error: SyntaxError: Unexpected token N. I guess this is because one of the properties looks like this:
{ ..., "SomeIntProp" : NumberLong(70) }
JavaScript parser simply doesn't understand Bson data type: NumberLong.
How should I convert BsonDocument to JSON so that the output would omit NumberLong?
There is no easy way to solve this, I worked out a solution by writing my own parsing function which understands the MongoDB BSON types and does the conversion. The native JSON.parse only understands the types used by the JavaScript. Here is my version:
https://gist.github.com/Hrish2006/8270187
You probably will not need the html snippets in the code.