My code wont print my object - javascript

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);

Related

Access JSON object from another file in Javascript

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);

Node.js: Parsing a json-ld / JSON with "#"-symbol

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');

Print data from json file

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/

Read JSON String Shown In URL Using Javascript

i am trying to create a simple web app that gets the latitude and longitude stored in a JSON string and uses them to place markers on a google map. Currently, I have a program on a server which retrieves a JSON string with data when a URL is entered into a web browser. The JSON string produced is as follows:-
{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}
What method could i use in JavaScript that would allow me to get the JSON string that is produced?
P.S I know I will need to parse the text afterwards to make a JSON Object, this is something that can be done afterwards.
Use the Jquery library's get method to request the data from the server. Here is a link to a simple W3 tutorial : http://www.w3schools.com/jquery/ajax_get.asp
Your code will look something like this:
$("button").click(function(){
$.get("/your/server/url",function(data){
var result = JSON.parse(data);
// Process result.employees
});
});
You could use
var x = JSON.parse('{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');
and then access it with:
x["employees"][0]["lat"];
try this for normal strings:
JSON.parse(str)
or if you're using AJAX to get that Json you can use as following:
$.get(..,'json')
OR
$.post(..,'json')

xPages - set javascript variable by reading JSON from URL

I have an xAgent (based on JSONandRest example in openntf by Nikolas Heildoff) which returns me a json. this xpage is nothing by there is a call to java method which returns JSON.
My problem is to have this JSON read into a JS variable so I am able to play with it.
I would like to do something like:
var myJson = getJson("Json.xsp")
Thanks in advance
Arun
You can use the fromJson method:
var json = "{a:'123', b: 'abc'}";
var obj = fromJson( json );
println( obj.a );
This sends 123 to the console.

Categories