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');
Related
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);
I have a CSV file that looks like this:
# Meta Data 1: ...
# Meta Data 2: ...
...
Header1, Header2...
actual data
I'm currently using the fast-csv library in a NodeJS script to parse the actual data part into objects with
const csv = require("fast-csv");
const fs = require("fs");
fs.createReadStream(file)
.pipe(csv.parse({
headers:true,
comment:"#", // this ignore lines that begin with #
skipLines:2 })
)
I'm skipping over the comments or else I won't get nice neat objects with header:data pairs, but I still want some of my meta data. Is there a way to get them? If not with fast-csv, is there another library that could accomplish this?
Thanks!
Edit: My current work around is to just regex for the specific meta data I want, but this means I have to read the file twice. I don't expect my files to be super big so this works for now but I don't think it's the best solution.
I have written a POSTMAN call to a server that responds with a list of items in JSON like below:-
{
"count": 6909,
"setIds": [
"1/7842/0889#001",
"2/4259/0166#001",
"ENT0730/0009",
"9D/11181#002",
"1/9676/0001#001",
"2/4718/0001#004",
"2/1783/0044#001",
"1/4501/0001#001",
"1/2028/0002#002",
"2/3120/0079#001",
"2/1672/0024#001",
"2/3398/0064#001"
}
I want to make calls to another server using the value of the setID each time and iterate through all of these so that I end up calling the server thousands of times to verify the response from that server. The problem I have is that the second server expects the set id to be in a form where the forward slashes are converted to underscores and the hashes to dots, so
"1/7842/0889#001"
becomes
"1_7842_0889.001"
I have code that converts one to the other in POSTMAN
var jsonData = pm.response.json()
for (var i=0; i<jsonData.setIds.length; i++)
{
var new_j = jsonData.setIds[i].replace (/#/g, ".");
var new_i = new_j.replace (/\//g, "_");
}
})
This works fine line by line it creates the right thing in the console of POSTMAN but obviously what I really need to do is save the entire JSON in the right form to a file and then read from that file line by line using the corrected data. I don't seem to be able to save the data in a file in the right form using my code and I suspect I am missing something simple. Is there a way to write a file line by line from in side postman or in a script and manipulate the data as I'm creating it?
Alternatively I guess I could read from the JSON I have saved i.e. the full response and iterate through that manipulating the data as a pre-request script?
I have tried to do something like this using environmental variables - so in my first call I do:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable('setIds', JSON.stringify(jsonData));
and then in my second call to the express server where I want to send my payload I run a pre-request script that I thought would work using the env variable but this fails as it doesn't seem to like the {...
SyntaxError: Unexpected token {
I think there are probably some neat ways of solving this either doing all of this outside of POSTMAN in javascript but I'm a little lost where to start. Any help appreciated
Would tell you are plaing with content, but not setting it back to JSON object ??
jsonData.setIds[i] = new_i;
can help or you can use 2x replace it in a string and convert back to make it easier (in case there are no / or # somewhere else).
var src = {
"count": 6909,
"setIds": [
"1/7842/0889#001",
"2/4259/0166#001",
"ENT0730/0009",
"9D/11181#002",
"1/9676/0001#001",
"2/4718/0001#004",
"2/1783/0044#001",
"1/4501/0001#001",
"1/2028/0002#002",
"2/3120/0079#001",
"2/1672/0024#001",
"2/3398/0064#001"
//...
]
}
var str = JSON.stringify(src, null, 4);
str = str.replace(/\//g,'_').replace(/#/g,'.');
console.log(str);
var res = JSON.parse(str);
console.log(res);
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 have json file with given data (total.json)
var data = {"trololo":{"info":"61511","path".... }}
I need to get object "info" and then print data "61511" in alert window
I include my json like
var FILE = 'total'
var data_file_names = {};
data_file_names[FILE] = 'total.json';
And then i use it like
var data_trololo = data_file_names[FILE];
Plese, help me print object "info". Maybe there is another way to solve this problem
You need to make an ajax call to the json file. Then you can access the array like the below example.
Note : Your json wasn't properly formatted.
var data = {
"trololo":{
"info": ["61511","path"]
}
};
console.log(data.trololo.info[0]); //this one will print 61511
Usually one can make an ajax call to read the file on the server.
But if you are ok with using HTML5 features then go through the link find out how to read the file on the browser itself. Though File API being part of HTML5 spec is stable across browsers.
http://www.html5rocks.com/en/tutorials/file/dndfiles/