Fetch JSON data from a file - javascript

I got a very simple txt file in JSON format:
{
"menu": "File1",
"bday": [
{
"name": "teo",
"date":"22"
},
{
"name": "john",
"date": "9"
},
{
"name": "maria",
"date": "15"
}
]
}
All I want is to just fetch the data and print them. Like:
teo : 22
john:9
...etc...
I don't care about this. I just want to fetch the data.

Your answer is plainly XMLHttpRequest, which is multi-browser compatible JavaScript without need for a library. You can always create your own library for some backward-compatibility.

Put the JSON in a file on your server (for example, data.js) and then use jQuery to fetch the file. Something like this:
var json;
$.getJSON("data.js", function(data){
json = data;
});

Related

Javascript parse JSON error, but works fine in validator

When I try to parse this JSON (Discord webhook):
{
"content": "this `supports` __a__ **subset** *of* ~~markdown~~ 😃 ```js\nfunction foo(bar) {\n console.log(bar);\n}\n\nfoo(1);```",
"embed": {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 16324973,
"timestamp": "2018-12-18T09:22:12.841Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "🤔",
"value": "some of these properties have certain limits..."
},
{
"name": "😱",
"value": "try exceeding some of them!"
},
{
"name": "🙄",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
}
Using this code:
var parsed = JSON.parse(req.body)
I get this error:
SyntaxError: Unexpected token o in JSON at position 1
But if I use a website such as
https://jsonformatter.curiousconcept.com
To validate the JSON, it says the JSON is valid.
What is wrong here?
UPDATE
I'm using an express server to simulate discord server, so it sends web hooks to the express server instead, I get the JSON using req.body.
This happens because JSON is a global object (it's the same object where you read the method parse!), so when you invoke JSON.parse(JSON) javascript thinks you want to parse it.
The same thing doesn't happen when you pass the variable to the validator, because it will be assigned to a local variable:
let JSON = "{}";
validate(JSON);
function(x) {
JSON.parse(x); // here JSON is again your global object!
}
EDIT
According to your updated question, maybe it happens because you already use bodyParser.json() as middleware, and when you use it, req.body is already an object and you don't need to parse it again.
Trying to parsing an already parsed object will throw an error.
It would be something like without using JSONStream:
http.request(options, function(res) {
var buffers = []
res
.on('data', function(chunk) {
buffers.push(chunk)
})
.on('end', function() {
JSON.parse(Buffer.concat(buffers).toString())
})
})
For using it with JSONStream, it would be something like:
http.request(options, function(res) {
var stream = JSONStream.parse('*')
res.pipe(stream)
stream.on('data', console.log.bind(console, 'an item'))
})
(OR)
Here is the Some Steps for this issue..
You Can use lodash for resolving this.
import the lodash and call unescape().
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);

How to escape commas in JSON for read by highchart

I have the following JSON, I want add commas in between the numbers, but when ever I do that the JSON fails. My workign version of the code can be seen in the fiddle link below
FIDDLE
I want to change this 11488897 to 11,488,897
Is this possible to do? How can this be done?
thanks for your help
[{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}]
If you want to preserve commas, you just need to use strings:
"data": ["48,353,330","38,079,817","37,130,929","1,957,317"]
Whether that's a good idea or not is another story. Typically you'd want your JSON returned by the server to include raw (i.e., integer) data, and then just format it however you want when you're actually using it. That way the same RPC endpoint can be used to fetch data for use in a chart or for any other purpose that might arise later on.
try this:
var data = [{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}];
data.forEach(function(obj) {
obj.data = obj.data.map(function(item) {
if (typeof item == 'number') {
return item.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return item;
}
});
});
alert(JSON.stringify(data, true, 4));
I don't know if it's cross-browser but if you do this
var number = 11488897;
number = number.toLocaleString('en');
You'll get the number (string) with commas on decimals

How to search and select an object in JSON

Consider a JSON like this:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
},
{
"type": "something_else",
"where": "NY"
}]
I want to search in the JSON value with a key (for example type='person') and then select a whole object of matched item in JSON. For example when I search for type='person' I expect this value:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
}]
Because it's a really big JSON value, I don't want to do a brute-force search in all nodes, so I think the only way is using Regular Expressions but I don't know how can I write a Regex to match something like above.
I'm using NodeJs for the application.
Using underscore.js#where:
var results = _(yourObject).where({ type: 'person' })
If your data set is very very big [e.g. 10k or so], consider filtering / paginating stuff server side.
Plain javascript :
var results = dataset.filter(function(p) {
if(p.type == 'person')
return true;
});
If the requirement is to scan multiple times through the collection, the following one time construction overhead might be of worth.
Use hashing based on values of type.Convert the current data structure to hash map.
var hashMap ={
};
hashMap['person'] =[{},{}];
Hope this helps you.
Use
$.grep(jsonarrayobj,function(n, i){
if(n.type==="person")
{}
})

Ember.js REST adapter handling different JSON structure

I'm using REST adapter, when I call App.Message.find() Ember.js makes call to the /messages to retrieve all messages and expect to see JSON structure like this:
{
"messages": [] // array contains objects
}
However API I have to work with response always with:
{
"data": [] // array contains objects
}
I only found the way1 to change namespace or URL for the API. How to tell REST adapter to look for data instead of messages property?
If this is not possible how to solve this problem? CTO said we can adapt API to use with REST adapter as we want, but from some reason we can't change this data property which will be on each response.
Assuming you are ok with writing your own adapter to deal with the difference, in the success callback you can simply modify the incoming name from "data" to your specific entity -in the case above "messages"
I do something like this to give you and idea of what if possible in a custom adapter
In the link below I highlighted the return line from my findMany
The json coming back from my REST api looks like
[
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
I need to transform this before ember-data gets it to look like this
{
"sessions": [
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
}
https://github.com/toranb/ember-data-django-rest-adapter/blob/master/packages/ember-data-django-rest-adapter/lib/adapter.js#L56-57
findMany: function(store, type, ids, parent) {
var json = {}
, adapter = this
, root = this.rootForType(type)
, plural = this.pluralize(root)
, ids = this.serializeIds(ids)
, url = this.buildFindManyUrlWithParent(store, type, ids, parent);
return this.ajax(url, "GET", {
data: {ids: ids}
}).then(function(pre_json) {
json[plural] = pre_json; //change the JSON before ember-data gets it
adapter.didFindMany(store, type, json);
}).then(null, rejectionHandler);
},

Using JQuery .getJSON to read in an array

I aam trying to GET an array from a JSON file using JQuery's ajax methods. Specifically, I want to make the ajax request on document load and use the acquired data in other functions.
Here is my code:
$(document).ready(function() {
getJSON();
clickEvents();
});
function getJSON() {
$.getJSON('goods.js', function(data) {
crazyFun(data.Goods);
addScores(data.karma);
});
}
}
function addScores(karma) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
function crazyFun(Goods) {
for (var i = 0; i < Goods.length; i++) {
var alpha= $('#template').clone();
alpha.removeAttr('id');
alpha.find('div.picture').attr('id', Goods[i].picture);
alpha.find('h2').html(Goods[i].header);
alpha.find('p').html(Goods[i].text);
alpha.find('div.notification').attr('id', Goods[i].notification);
$('#repeater').append(alpha);
}
}
karma and Goods are the name of the arrays in the JSON file.
What am I doing wrong?
Here is my JSON array for karma:
{
Goods : [{
"header": "Apple",
"text": "hi"
"picture": "appleImage",
"notification": "appleNote"
}, {
"header": "Pear",
"text": "hi",
"picture": "pearImage",
"notification": "pearNote"
}, {
"header":hi",
"picture": "bananaImage",
"notification": "bananaNote"
}, {
"header": "Dog",
"text": "hi",
"picture": "dogImage",
"notification": "dogNote"
}, {
"header": "Cat",
"text": "hi",
"picture": "catImage",
"notification": "catNote"
}, {
"header": "Snake",
"text": "hi",
"picture": "snakeImage",
"notification": "snakeNote"
}],
karma : [{
"karmaYinYangScore": "200",
"KarmaGiveScore": "40",
"KarmaTakeScore": "99",
"ItemsGiveScore": "20",
"ItemsTakeScore": "77"
}];
}
I can only guess what your data looks like, but since you said "karma and Goods are the name of the arrays", I'm going to assume we're talking about something like this:
{
karma: [{
karmaYinYangScore:'some value',
KarmaGiveScore:'some value',
KarmaTakeScore:'some value',
ItemsGiveScore:'some value',
ItemsTakeScore:'some value'
}
],
Goods: ['more','array','values']
}
If that's the case, we've got a few issues in your code.
First, getJSON returns one data result, so you should be referencing only that data returned.
function getJSON() {
$.getJSON('goods.js', function( data ) {
crazyFun( data.Goods ); // reference Goods array from data response
addScores( data.karma ); // reference karma array from data response
});
}
Then, your .addScores() function doesn't accept a parameter. You need some reference to receive the array being passed.
// Reference to the array being passed to the function
// ---------------v
function addScores( karma ) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
These are the only errors I see. Beyond that, the solution depends on the actual data structure of the response.
According to jQuery's documentation on the getJSON function (http://api.jquery.com/jQuery.getJSON/), your callback's parameters appear to be misleading. Your callback...
function(Goods, karma) {
crazyFun(Goods);
addScores(karma);
}
...appears to be expecting the arrays of data to be passed to it automatically, but jQuery actually passes the whole JSON result as the first parameter, and the status of your request as the second parameter, regardless of how the JSON is structured. Your callback should probably look more like this:
function(json, status) {
crazyFun(json.Goods);
addScores(json.karma);
}
This assumes that your JSON is well formed, and that the "Goods" and "karma" properties are properties of the root object. You may need to modify the callback if your JSON is structured differently.

Categories

Resources