Parsing JSON file with AngualrJS - javascript

I'm learning AngularJS and running some tests, but I'm having the following problem: I'm trying to read a JSON file, parse it into an object and show its properties on the screen. I read that $http parse the JSON text automatically, so I wrote the following code:
$http.get("/people").success(
function(data, status, headers, config) {
$scope.data = data.people;
}
);
This is my JSON file:
{ "people": [
{
"id": "0",
"name": "Cave Jhonson",
"company": "Aperture Science"
},
{
"id": "1",
"name": "Gustavo Fring",
"company": "Los Pollos Hermanos"
}
]
}
Which is in my project folder. I'm running a Python server. Finally, I'm trying to show the information with a simple HTML:
<p>{{data.people[0].name}}</p>
But when I open the page in Firefox the information doesn't show up and I get this error message: " Error: JSON.parse: expected property name or '}' "
My JSON is valid, so I can't understand why $http is not parsing it.

this line is inccorrect: <p>{{data.people[0].name}}</p>
You already put the code on scope in data so use that
<p>{{data[0].name}}</p>
Or you can use ng-repeat to show all the records like this
<div ng-repeat='item in data'>
<p>Id: {{item.id}}, Name: {{item.name}}, company: {{item.company}}</p>
<div>

Related

Create and Read JSON file

I created a JSON file as follows
{
"fooditems" : [
{
"name": "pizza",
"type": "fastfood",
"price": 10
},
{
"name": "apple",
"type": "fruit",
"price": 1
}
]
}
created a JS file to read the JSON file
const data = require("./data.json");
data1 = JSON.parse(data);
data1.foodData.forEach( foodItem => console.log(foodItem));
When I run the JS, I get error for the json file
Syntax error: Unexpected token o in json at position 1
at JSON.parse
You don't need to parse data since it's already and object. The following should work.
const data = require("./data.json");
data.fooditems.forEach( foodItem => console.log(foodItem));
Note foodData was change to fooditems based on the contents of the data.json file.
Your initial data JSON contains "fooditems", but in the JS file you are trying to process the "foodData". Change the "foodData" to "fooditems" and it should work.
I think that you are trying to access invalid object key in your JS file on the last line.
Instead of
data1.foodData
put
data1.fooditems

Pug - retrieving keys from a JSON object

I'm trying to create a single page website using Pug's templating engine and JSON as a database. Ultimately I'd like to store my different "pages" in the JSON file, and then render that JSON using different variables/mixins in my Pug template, but I keep receiving the errors, cannot read property "company" of undefined.
Any help would be greatly appreciated.
This is my Gulp task to build my Pug files, and pipe the JSON into the template:
// build the Pug files into HTML
gulp.task('build-pug', function buildHTML(){
var dataFile = 'source/javascript/pages.json';
return gulp.src('source/**/*.pug')
.pipe(data(function(file){
return JSON.parse(fs.readFileSync(dataFile));
}))
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('public'))
.pipe(browserSync.reload({
stream: true
}));
});
This is my pages.json file:
{
"pages": [
{
"year": "2016",
"company": "Abacus",
"home": "./assets/images/2016/home/abacus.png",
"home-url": "http://abacus.com",
"login": "./assets/images/2016/login/abacus.png",
"login-url": "http://abacus.com/login",
"pricing": "./assets/images/2016/pricing/abacus.png",
"pricing-url": "http://abacus.com/pricing"
},
{
"year": "2016",
"company": "Alfred",
"home": "./assets/images/2016/home/alfred.png",
"home-url": "http://alfred.com"
}
]
}
This is in my index.pug file where I'm trying to call keys from my JSON:
section.pricing
h1 Pricing Pages
div.content.pricing
each page in pages
p= page.pages.company
what about replacing your last line in index.pug with
p= page.company

How to add text to beginning and ending of JSON to make it JSONP

I'm working on a project, I can manually add a beginning name and parenthesis: bio(
and an ending ) to the end of my JSON data to make it callable as JSONP.
I am going to do this to about 200 files which is why I'm trying to find a solution to do this in code.
I've tried using regex, converting to a string, trying to convert back, etc, and nothing seems to work.
My abbreviated JSON data is below:
{
"Directory": {
"workbooks": ["/xl/workbook.xml"],
"sheets": ["/xl/worksheets/sheet1.xml"],
"style": "/xl/styles.xml",
"defaults": {
"xml": "application/xml",
"rels": "application/vnd.openxmlformats-package.relationships+xml"
}
},
"Workbook": {
"AppVersion": [null],
"Sheets": [
[null]
],
"CalcPr": [null],
"xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}
What I want is:
bio({ <--------
"Directory": {
"workbooks": ["/xl/workbook.xml"],
"sheets": ["/xl/worksheets/sheet1.xml"],
"style": "/xl/styles.xml",
"defaults": {
"xml": "application/xml",
"rels": "application/vnd.openxmlformats-package.relationships+xml"
}
},
"Workbook": {
"AppVersion": [null],
"Sheets": [
[null]
],
"CalcPr": [null],
"xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}) <-------
I've gotten closest with Stringify and regex:
var myString = JSON.stringify(workbook);
var change = myString.replace(/^/,"bioInfo(").replace(/$/,")”);
When I try to change it back to an object so I can use it though, it fails saying:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
I've tried eval as well trying to get it to change back to an object but it just doesn't seem to work.
Hopefully my dilemma is clear and someone knows a good way to do this in Javascript or Jquery.
Thanks in advance.
You don't need anything as complicated as you are making it. Just concatenate your strings.
var jsonp = "bio(" + json + ");"
I've gotten closest with Stringify
JSON is already a string. You only need to stringify something if you have a JavaScript data structure and want to convert it to JSON.

AngularJs search still reads non existent data

I've come across something so bizarre. I had this below set up to read from a data.json file. It should show up a list of people. Instead it's ignoring the json file and is reading out non existing words! I just want it to read from data.json. Even if I delete "data.json" , the search function still prints out these words which don't exist.
As you can see from the photo, it's showing up a list of words that I DO NOT have stored anywhere in my code or on my server. It's puzzling me.
<body ng-app="personApp">
<div class="container">
<header></header>
<div ng-controller="PersonListCtrl">
<div class="bar">Search:
<input ng-model="query">
</div>
<ul class="">
<li ng-repeat="person in persons | filter:query">{{person.name}}</li>
and
var personApp = angular.module('personApp', []);
personApp.controller('PersonListCtrl', function ($scope, $http) {
$http.get('js/data.json').success(function (data) {
$scope.persons = data;
})
});
data.json
[{
"name": "Mike Doe"
}, {
"name": "Jhon Doe"
}, {
"name": "Sam Doe"
}, {
"name": "Sam Doe"
}, ];
Go to browser console -> Network.
Most probably you will see 304 status of your request, that means ajax request was cached by browser. Either clean cache, add query string to request etc.

Sencha Touch : How to get the simple json file as response using JSONP?

I am trying to make a simple JSONP call to get a json file which is loaded on the remote server.
Here is my simple json file loaded on the server.
{
"login": [
{
"themename": "NO",
"themeId": "1"
}
],
"homePage": [
{
"themename": "NO",
"themeId": "1"
}
],
"transactionDetails": [
{
"themename": "NO",
"themeId": "1"
}
]
}
My Controller code which calls this file to get the data
Ext.data.JsonP.request(
{
url : 'http://xx.xx:8080/ThemeSelector.json',
callback : 'someCallback' ,
someCallback: function(success, result) {
var text = result.responseText;
var object = Ext.decode(text);
themeName = object['homePage'][0].themename;
}
});
I am getting the error "Uncaught SyntaxError: Unexpected token : "
I know that the response should be wrapped in the object but not able to make the exact correction in json file and my code. Any help please?
Thanks
JSONP requires that the response be in the form of a JavaScript function call, passing the actual JSON object as the parameter. Plain JSON won't (can't) work.
The exact details of how the function call should look (in particular, the function name) can vary, but usually it's a parameter added to the HTTP request. The server should construct the response based on that parameter's value.
To work with JsonP, your json response should contain the callback parameter you've sent. Without that, callback function will not get called and produces error since it does require that. In your case, you just have plain JSON file on server to serve. So you cant use JsonP directly with this file.
If you've some control over server, then you can write a script that can do this for you like -
<?php
header('Content-Type: text/javascript');
$response = file_get_contents('ThemeSelector.json');
echo $_GET['someCallback'] . '(' . $response .' );';
?>
Then received json response will look something like -
Ext.data.JsonP.callback2 (
{
"login": [
{
"themename": "NO",
"themeId": "1"
}
],
"homePage": [
{
"themename": "NO",
"themeId": "1"
}
],
"transactionDetails": [
{
"themename": "NO",
"themeId": "1"
}
]
}
)

Categories