Extracting JSON data into Javascript object array - javascript

I have a JSON file with dummy articles in it for testing purposes. I'm trying to extract the information from the JSON file using jQuery to create an array of objects using the pulled information.
Here's my JSON file:
{
"news": [
{
"title": "Test 1",
"author": "Chicago Tribune",
"source": "http://www.chicagotribune.com/",
"preview": "Long-simmering . . .",
"picture": "IMG"
},
{
"title": "Test 2",
"author": "New York Times",
"source": "http://www.nytimes.com/",
"preview": "Information . . .",
"picture": "IMG"
},
{
"title": "Test 3",
"author": "Chicago Tribune",
"source": "http://www.chicagotribune.com/",
"preview": "Blah blah blah . . .",
"picture": "IMG"
}
]
}
Here's my Javascript file:
// Article array
var articles = [];
// Article 'class'
function Article (title, author, preview, picture) {
this.title = title;
this.author = author;
this.preview = preview;
this.picture = picture
}
// Pull data from JSON file
$.getJSON('data.json', function(data) {
$.each(data.news, function (i, j) {
articles.push(new Article(j.title, j.author, j.preview, j.picture));
});
});
for (i = 0; i < articles.length; i++) {
Console.log('Article ' + i + ": " + articles[i].title);
}
The articles array is not filling up and there doesn't seem to be any objects created. My next step would be iterating through each file in the array and posting that data to a page using the newly-filled array of articles.

Three things:
Your JSON is invalid. You're likely getting it pasted wrong, but it should look like this:
ex:
{
"news": [
{
"title": "Test 1",
"author": "Chicago Tribune",
"source": "http://www.chicagotribune.com/",
"preview": "Long-simmering . . .",
"picture": "IMG"
},
{
"title": "Test 2",
"author": "New York Times",
"source": "http://www.nytimes.com/",
"preview": "Information . . .",
"picture": "IMG"
},
{
"title": "Test 3",
"author": "Chicago Tribune",
"source": "http://www.chicagotribune.com/",
"preview": "Blah blah blah . . .",
"picture": "IMG"
},
]
};
the $.each() will loop through each element of the news array, so you will only get one element into your anonymous function. Try this instead:
ex:
$.getJSON('data.json', function(data) {
$.each(data.news, function (i) {
articles.push(new Article(i.title, i.author, i.preview, i.picture));
});
});
You're running into async issues because the for loop executes before your JSON arrives. Try adding in your for loop inside your $.getJSON call if you have code that depends on the articles being there. Here's a great explanation on async behavior.
Additionally, whenever in doubt as to what you're receiving in your parameters, add a debugger; inside your function - that way you can inspect and ensure you're getting what you inspect.

Related

Path with '/' in json-server db.json

i use server-json to have a fake API, i have the path "playbook/active" in data.json
"playbook/active": [{
"description": "This playbook will install haproxy",
"name": "Testing playbook 3",
"tag": [
"loadbalancer",
"charge"
],
"path": "/etc/ansible/haproxy.yml",
"type": "action",
"id": "4bb107be-9efe-11e9-b3e5-bc5ff4901aa5"
},
{
"path": "google.com",
"description": "This is the playbook before execution",
"tag": [
"webserver",
"tomcat"
],
"id": "faa746b4-9cb7-11e9-9b94-bc5ff4901aa5",
"name": "mysql"
}
]
but i have this error
Error: Oops, found / character in database property 'playbook/active'.
I change to "playbook/active" but same error
Providing a complete answer (showcase example)
Configuring db.json and routes.json can do the trick for you:
db.json
{
"playbookActive": [
{
"id": 1,
"name": "Active Playbook 1",
"description": "Description 1"
},
{
"id": 2,
"name": "Active Playbook 2",
"description": "Description 2"
}
]
}
routes.json
{
"/playbook/active": "/playbookActive",
"/playbook/active/:id": "/playbookActive/:id"
}
Note: the mapping in routes.json is goes like this: [expanded/endpoint]: aliasEndpoint where aliasEndpoint should match the one from db.json.
package.json
{
...
"scripts": {
"api": "json-server [path-to-db.json] --routes [path-to-routes.json] --no-cors=false"
},
...
}
Verify the routing on start (logs from npm run api):
Resources
http://localhost:3000/playbookActive
Other routes
/playbook/active -> /playbookActive
/playbook/active/:id -> /playbookActive/:id
Home
http://localhost:3000
Examples
GET → http://localhost:3000/playbook/active
Response contains a list with all the active playbooks:
[
{
"id": 1,
"name": "Active Playbook 1",
"description": "Description 1"
},
{
"id": 2,
"name": "Active Playbook 2",
"description": "Description 2"
}
]
GET → http://localhost:3000/playbook/active/2
Response contains the active playbook that matches id=2:
{
"id": 2,
"name": "Active Playbook 2",
"description": "Description 2"
}
Check the error message:
Oops, found / character in database property 'dossier/la'.
/ aren't supported, if you want to tweak default routes, see
https://github.com/typicode/json-server/#add-custom-routes
It seems that slashes are not supported.
The solution is to create a routes.json file containing the mapping for your url.
For example the contents of this file could be:
{
my-awesome-endpoint": "playbook/active"
}
For example:
db.json
"list": [
{
"name": "abcde",
"tel": "123454323",
"id": 5
}
]
routes.json
{
"/v1/list?type=hot": "/list"
}
start command:
npx json-server --watch db.json --routes routes.json

Error - Our JSON is formatted incorrectly. Events won't show for Full Calendar

How can we format our API Json like the first block of code below? Do we need to put it in an array, string, object? Our issue is that Full Calendar can get events from the first block of code, but not ours, the second block of code.
http://www.json-generator.com/api/json/get/ccUKVDYErS?indent=2
[
{
"start": "2014-08-01",
"title": "All Day Event"
},
{
"start": "2014-01-07",
"end": "2014-08-10",
"title": "Long Event"
},
{
"start": "2014-08-09T16:00:00",
"id": 999,
"title": "Repeating Event"
},
{
"start": "2014-08-16T16:00:00",
"id": 999,
"title": "Repeating Event"
},
{
"start": "2014-08-12T10:30:00",
"end": "2014-08-12T12:30:00",
"title": "Meeting"
},
{
"start": "2014-08-22T12:00:00",
"title": "Lunch"
},
{
"start": "2014-08-13T07:00:00",
"title": "Birthday Party"
},
{
"url": "http://google.com/",
"start": "2014-08-28",
"title": "Click for Google"
}
]
Our API currently looks like this (everything is a string),
[{"start":"2016-04-12","end":"2016-04-12","title":"Calendar 1","id":"a41380d1fbbaa819"}]
Try this it will work :
As per your question.
//JSON Text
var obj = '[{"start":"2016-04-12","end":"2016-04-12","title":"Calendar 1","id":"a41380d1fbbaa819"}]';
//Convert JSON String in JSON Object
console.log(JSON.parse(obj));
Output :
As per your requirement :
You have to pass these values in the url and making AJAX call to get the JSON according to these values.
var start='2016-04-12';
var end='2016-04-12';
var title='Calendar 1';
var id='var start='2016-04-12';';
$.ajax({
type: "POST",
dataType: "json",
url: "data.php", //Relative or absolute path to chat.php file
data: 'start='+start+'&end='+end+'&title='+title+'&id='+id,
success: function(data) {
alert(data); // JSON From the URL
}
});
return false;
}
Now you have to use server side language(PHP,Java) to create the JSON based on these values.
Working Fiddle : https://jsfiddle.net/pr2daL7r/
Talking about your API you are saying that '(everything is a string)'.
To convert string into JSON use JSON.parse() docs
var validJSON = JSON.parse('[{"start":"2016-04-12","end":"2016-04-12","title":"Calendar 1","id":"a41380d1fbbaa819"}]');
Will return:
[{
"start": "2016-04-12",
"end": "2016-04-12",
"title": "Calendar 1",
"id": "a41380d1fbbaa819"
}]

Merge geojson based on unique ID

I'm a beginner in Javascript so please exuse this probably dumb question. I want to merge two json files based on unique object id.
Number one look like this:
"features": [{
"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}},
{"id": "3876803",
"properties": {"name":"another name"...}}...]
Number Two looks like this:
"features": [{
"id": "3876803",
"properties": {
"description": "some description",
"website": "afancywebsite"}},
{"id": "3876803",
"properties": {...}}]
The Elements in the second Json are not in the same order and not all elements of the first file exist in the second.
The Result should look like this:
"features": [{
"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}},{
"id": "3876803",
"properties": {
"name":"another name",
"description": "some description",
"website": "afancywebsite"}}]
I started coding this but I have no idea how to get it working...
for(var i in json1.features){
for (var z in json2.features){
if (json1.features[i].id===json2.features[z].id){
json1.feature[i].properties = json2.features[z].properties}}}
This will do the job:
var features = [
{"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}
},
{"id": "3876803",
"properties": {
"name":"another name"
}
}
];
var features2 = [{
"id": "3876803",
"properties": {
"description": "some description",
"website": "afancywebsite"
}
}
];
features.map(function(feature){
var matchedArray = features2.filter(function(feature2){
return feature2.id === feature.id;
});
if(matchedArray && matchedArray[0]){
for(var attr in matchedArray[0].properties){
feature.properties[attr] = matchedArray[0].properties[attr];
}
}
});
We start by using Array.map() to run through the 'features' array, one by one.
Then we use Array.filter() on the features2 array which gives us an array containing the only object in features2 (matched[0]) which has the same id as feature.id.
If there's a match, then we run through the 'properties' in the features2 object using a 'for in' loop and copy them to the 'feature' object.
If you want to get advanced info about this check out this stackoverflow question: How can I merge properties of two JavaScript objects dynamically?. For example, if you're writing bullet-proof javascript you should use 'hasOwnProperty' in a for in loop.
You may also want to guard against properties in 'features2' overwriting a property with the same name in 'features'.
However if you would like to keep your code more or less as it was this also works:
for(var i in features){
for (var z in features2){
if (features[i].id===features2[z].id){
for(var attr in features2[z].properties){
features[i].properties[attr] = features2[z].properties[attr];
}
}
}
}

Json array into select box with php

I hope someone can help me with this issue I have. What I want is a select box, which is getting filled from a json file. The problem is I have a strange kind of json file which I dont know if its array or object.
Here is how it loosk like:
{
"Id": 4,
"Name": "Testing Demo",
"OpeningHours": [
{
"Name": "Monday",
"Hours": "Kl. 09:30:00 - 21:00:00"
}
],
"Address": {
"Street": "Johnson road",
"StreetNumber": "5",
"Town": "London"
},
"Phone1": "4123213414",
"Phone2": null,
"Documents": null,
"Messages": [
{
"Title": "We are on the way",
"Body": "fine",
"Created": "01-02-2014"
},
{
"Title": "Get the stuff",
"Body": "To be ready",
"Created": "01-01-2014"
}
],
"Employees": [
{
"Name": "John Hood",
"Description": "officer",
"ProfileImageUrl": "http://grfx.cstv.com/photos/schools/kty/sports/m-baskbl/auto_headshot/9265204.jpeg"
},
{
"Name": "John hood 2",
"Description": "athletic",
"ProfileImageUrl": "http://grfx.cstv.com/photos/schools/kty/sports/m-baskbl/auto_headshot/9265204.jpeg"
}
]
}
How Iam going to show values of ID and the name?
This code it doesnt work which I dont know if Iam doing it even correctly..
(function($) {
$(document).ready(function() {
$('<tr class="form-field form-required"></tr>').append(
$('<th scope="row">New field</th>')
).append(
$('<td></td>').append(
$('<select id="release-list"></select>')
).append(
$('<p>Explanation about your new field</p>')
)
).insertAfter('#wpbody-content table tr:eq(2)');
});
$.getJSON('../../cache/path.json', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
$('<option/>').attr('value', val[key]["Id"]).html('value' + val[key]["Name"]).appendTo(select);
});
});
})(jQuery);
you can convert the data from json to array using JSON.parse()
http://www.dyn-web.com/tutorials/php-js/json/parse.php
Example:
var data = '{"first":[1,2,3],"second":[4,5,6]}';
var jsonData = JSON.parse(data);
alert(jsonData.first[1]);
alert(jsonData.second);

Simple json reading the api

I have a query that produces the following results:
{
"data": [
{
"id": "1107702400"
},
{
"id": "1149862205",
"likes": {
"data": [
{
"name": "Penelope Test",
"category": "Arts/entertainment/nightlife",
"id": "411133928921438",
"created_time": "2012-05-23T11:41:27+0000"
},
The first id I can access through:
response.data[i].id
How do I retrieve the second id? (the one that goes data-id-data-id ?)
I have this function:
for(i=0;i<response.data.length;i++)
{
testdiv.innerHTML += response.data.data[i].id + '<br/>' ;
}
Which lets me print the first id.
What do I need to do in order to print the second id?
In your example data
response.data[i].likes.data[0].id

Categories