'Unexpected Token' in json when calling an external file - javascript

I'm trying to implement backbone for a new project. Also installed are underscore, requirejs, jquery and bootstrap. Overall it is going well. I want to incorporate some static survey question data into one of my data models.
{
"defaultOptions": {
"1": "Strongly Agree",
"2": "Somewhat Agree",
"3": "Have Mixed Feelings",
"4": "Somewhat Disagree",
"5": "Strongly Disagree",
"6": "Have No Opinion",
"7": "Do Not Wish To Respond"
},
"questions": {
"1": {
"question": "Question 1",
"options": {}
},
"2": {
"question": "Question 2",
"options": {}
},
"3": {
"question": "Question 3",
"options": {}
},
"4": {
"question": "Question 4",
"options": {}
},
"5": {
"question": "Question 5",
"options": {}
}
}
}
I don't currently have access to the data API I will ultimately be using to build this project, so I'm currently working off of some dummy data exported from the previous iteration of this project (It's for the US Elections cycle, so it happens yearly). I'm trying to pull some static data out of the content model I'm using and put it into a separate file so it's out of my way and I don't have to worry about inadvertently messing it up. No big deal, right? I'm not crossing any domains, it all lives on the same server. I have another data set doing the same thing. I even ran the information through http://www.jsoneditoronline.org/ to make sure it was valid json.
So what's the problem? I get this error in chrome "Uncaught SyntaxError: Unexpected token : on line 2" and this error in FireFox 'SyntaxError: missing ; before statement "defaultOptions":', with the indicator pointing towards the : after defaultOptions.
I really have no idea why this is happening.
I am calling two json files, one right after the other:
var survey = require('/elections/data/surveyQuestions.json');
var endorsements = require('/elections/data/endorsements.json');
The endorsements.json file (and anything else called with require) doesn't have any issues. Here it is for reference:
[
"Abortion Rights Council",
"AFL-CIO",
"AFSCME",
"American Federation of Teachers",
"Building and Construction Trades Council",
"DFL Feminist Caucus",
"DFL Party",
"Education Minnesota",
"Freedom Club",
"GOP Feminist Caucus",
"Grassroots Party",
"Green Party of Minnesota",
"Independence Party",
"Libertarian Party of Minnesota",
"MAPE",
"Minnesota Citizens Concerned for Life",
"Minnesota Police and Peace Officers Association",
"National Association of Social Workers",
"Republican Party of Minnesota",
"Sierra Club",
"Stonewall DFL",
"TakeAction Minnesota",
"Taxpayers League of Minnesota",
"Teamsters DRIVE",
"United Auto Workers"
]
Does anybody have any thoughts as to what I'm missing?

RequireJS is expecting an AMD module when you call require(). You should use the RequireJS text plugin for loading text resources like JSON. Also look at this GitHub gist for a plugin to parse JSON specifically that's built on top of the text plugin.

Related

json-schema additional metadata

It is possible to add additional or custom metadata (other than title and description) to a json schema property?
Ideally I'd like to add some metadata like so:
//...
"properties": {
"contactFullName": {
"$ref": "#/definitions/fullName",
"custom": "my custom metadata here"
}
}
//...
Can you add something to definitions to allow that?
You don't have to do anything special to use additional metadata keywords. You can just use them. In JSON Schema it is not an error to include undefined keywords. Anything that doesn't have JSON Schema semantics should be quietly ignored. So, the following schema is completely valid and should not conflict with any validator implementation.
{
"title": "Foo",
"description": "All the foo you can GET",
"version": "1.0.3",
"author": "Jason Desrosiers",
"type": "object",
"properties": {
"id": { "type": "string" }
}
}
You could use the description property and put a certain structure in there that could then be interpreted and applied as needed (like JSON within a JSON schema, so to speak).

Having trouble finding the best way to search

I need to find a node.js module or some script or make something to search though data and find the most relevant results. I was originally going to use google custom search API to search the steam community market but I think that's unnecessary and limited. But before that I was ripping apart the string and putting it back together and getting price data from steam individually, it worked practically perfect but it was messy and limited.
I now use an API to get all the steam csgo market data, i need to search it for the most relevant result.
A query for the below might look like 'stained bs' 'karambit stained fn' 'st stained ft'
"★ Karambit | Stained (Battle-Scarred)": {
"last_updated": 1439785289,
"quantity": 5,
"value": 18855
},
"★ Karambit | Stained (Factory New)": {
"last_updated": 1439785289,
"quantity": 5,
"value": 26499 // yea thats $265 for a purely cosmetic digital item
},
"★ Karambit | Stained (Field-Tested)": {
"last_updated": 1439785289,
"quantity": 10,
"value": 20000
},
"★ Karambit | Stained (Minimal Wear)": {
"last_updated": 1439785289,
"quantity": 10,
"value": 20223
},
"★ Karambit | Stained (Well-Worn)": {
"last_updated": 1439785289,
"quantity": 8,
"value": 19302
},
I am having trouble knowing what I should do.
The Node.js community have de Node Package Manager (npm) that is a command line utility and a public repository.
Using the search feature on npmjs.com you can find very useful modules.
Also github.com is a public site with tons of Node.js or just JavaScript modules. You can use their "explore" feature and filter by language to find useful client and server side code
If you already have installed npm. So you can use:
npm search <ANYTERM>

Deployd - Data retrieved via AngularJS CORS

I am currently reading through "Pro AngularJS" by Adam Freeman. In going through the examples, he has the reader create a sports store app using Angular (of course) with a Deployd server resource. The Deployd resource is set up to return JSON data that is to be populated into the model. I am using NodeJS to run my server. It is currently setup on port 5000 (http://localhost:5000/sportsstore/app.html). The Deployd resource is running on port 5500 (http://localhost:5500/products). When hitting Deployd, the response is as follows:
[
{ "name": "Kayak", "description": "A boat for one person", "category": "Watersports", "price": 275, "id": "a1c999fc248b2959" },
{ "name": "Lifejacket", "description": "Protective and fashionable", "category": "Watersports", "price": 48.95, "id": "61303717cfad182e" },
{ "name": "Soccer Ball", "description": "FIFA-approved size and weight", "category": "Soccer", "price": 19.5, "id": "0fb5f67bdcbd992f" },
{ "name": "Corner Flags", "description": "Give your playing field a professional touch", "category": "Soccer", "price": 34.95, "id": "24385d315dd388b4" },
{ "name": "Stadium", "description": "Flat-packed 35,000-seat stadium", "category": "Soccer", "price": 79500, "id": "500fb6805905a856" },
{ "name": "Thinking Cap", "description": "Improve your brain efficiency by 75%", "category": "Chess", "price": 16, "id": "637d8a1f42e6fa1c" },
{ "name": "Unsteady Chair", "description": "Secretly give your opponent a disadvantage", "category": "Chess", "price": 29.95, "id": "73393312ec7dfab7" },
{ "name": "Human Chess Board", "description": "A fun game for the family", "category": "Chess", "price": 75, "id": "7871d02a662b0915" },
{ "name": "Bling-Bling King", "description": "Gold plated, diamon-studded King", "category": "Chess", "price": 1200, "id": "b59a3389a0e248bd" }
]
I am attempting to retrieve this data through use of $http.get:
$http.get("http://localhost:5500/products")
.success(function (data) { ... })
.error(function (error) { ... });
However, this keeps returning an error:
XMLHttpRequest cannot load http://localhost:5500/products. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.
Research shows that there are/were some issues with Angular and CORS, and that the headers had to be configured to run cross-domain requests. As a result, I added the following to my app.config:
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With']; // this isn't needed anymore, but was put here as a just-in-case
Despite having these settings added, I am still getting the error. The Deployd documentation says that it is automatically configured for CORS (Cross-Origin Requests) and will send the appropriate header information as long as the request did not contain invalid custom headers. I'm pretty sure my request does not contain invalid custom headers:
Accept: application/json, text/plain, */*
Cache-Control: max-age=0
Origin: http://localhost:5000
Referer: http://localhost:5000/sportsstore/app.html
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
My Question: Is there some other configuration I need to put in place in order to have Deployd configured to allow the CORS request to process? The book does not specify any of the special Angular header settings or anything else.
Bic, upgrade your version of deployd to version 0.6.10. This did the trick for me. I was now able to process a get request. It doesn't seem like it's an error with AngularJS code nor Adam Freeman's book.
In the book, he does mention that he includes the deployd program with the source code download on http://www.apress.com/9781430264484. That's version 0.6.9. I'm sure it works fine with it. It'll be easier than to try to find the 0.6.10 version.. which is what I did. Should you want that version, here it is:
https://www.versioneye.com/nodejs/deployd/0.6.10
It's not an installer so you'll have to paste it in your deployd directory, replacing the node_modules.
Just run "npm update" in your deployd installation folder and it will make sure you're updated to the latest version 0.6.10. This resolved the issue for me after reading javaauthority's answers (Thanks for that :)).
You can place your files (app.html, sportStore.js, ...) under the public folder of your deployd project and use the following URL
http://localhost:5500/app.html
What I did to solve that issue was starting Chrome with the "--disable-web-security" flag. But first go to Task Manager and close every chrome process you have there.
While I provided the correct answer and others have improved it, what if you're not using the Deployd web server mentioned in the book? I'm using Wildfly (JBOSS 8.X) and I had to make the CORS issue work for it. I created a simple Java class called CorsFilter. The imports should be fairly easy to find if you're running Wildfly.
Hope this helps other people who are having similar issues with different web servers.
Please note: responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
Notice the * in the above line? This would allow ANY requests to succeed. This is usually fine for local development work, but tighter security controls should be implemented for Production/Staging environments. For example, you could only accept request from a certain IP address.
import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
/**
* Class to .
* User: Java Authority
* Date: 12/6/2014
* Time: 12:38 PM
*/
#Provider
#ServerInterceptor
#HeaderDecoratorPrecedence
#WebFilter
public class CorsFilter implements ContainerResponseFilter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest r = (HttpServletRequest)request;
HttpServletResponse s = (HttpServletResponse)response;
chain.doFilter(request, response);
}
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
}
}
I used fiddler to modify the responses from deployd. This link will show how to add a custom rule to fiddler to add Access-Control-Allow-Origin: * header to all responses. It works great.
http://www.leggetter.co.uk/2010/03/19/using-fiddler-to-help-develop-cross-domain-capable-javascript-web-applications.html
Angular also sends custom headers that DPD rejects, put this in your code for dev to remove these and DPD will work:
delete $http.defaults.headers.common['X-Requested-With'];

Kartograph: Map Creation fails

Recently I started using Kartograph. I am inexperienced in SVG, so the map creation is creating headaches for me. After initial trouble creating a world map that outlines country borders - similar to this - and a few other things(city regions and some decorating elements), my problem boils down to a undocumented - or at least I haven't found it in the docs - error. I guess it is related with my ignorance towards the kartograph.py framework.
The json file I provide Kartograph looks like that:
{
"proj": {
"id": "lonlat",
"lon0": 20,
"lat0": 0
},
"layers": {
"background": {
"special": "sea",
"charset": "latin-1",
"simplify": false
},
"graticule": {
"special": "graticule",
"charset": "latin-1",
"simplify": false,
"latitudes": 1,
"longitudes": 1,
"styles":{
"stroke-width": "0.3px"
}
},
"world":{
"src": "ne_50m_admin_0_countries.shp",
"charset": "latin-1",
"simplify": false
},
"lakes":{
"src": "Lakes.shp",
"charset": "latin-1",
"simplify": false
},
"trees":{
"src": "Trees.shp",
"charset": "latin-1",
"simplify": false
},
"depth":{
"src": "DepthContours.shp",
"charset": "latin-1",
"simplify": false
},
"cities":{
"src": "CityAreas.shp",
"charset": "latin-1",
"simplify": false
}
}
}
I know the output file will be huge and the generation will take ages, but it is just a test. I will experiment with the "simplify" option later. Much of the code in the file is based on this tutorial. Also, the empty simplify clause might not be necessary, but kartograph complained about the lack of the option, so I added it.
The command I use is this one:
kartograph world.json -o world.svg
It runs for some time(I guess, parsing all the input files etc.) before aborting. Now, the error I am facing is this one:
cli.py, in render_map()
71: K.generate(cfg, args.output, preview=args.preview, format=format, stylesheet=css) kartograph.py, in generate()
46: _map = Map(opts, self.layerCache, format=format) map.py, in __init__()
50: me.bounds_poly = me._init_bounds() map.py, in _init_bounds()
192: features = self._get_bounding_geometry() map.py, in _get_bounding_geometry()
257: charset=layer.options['charset']
get_features() got an unexpected keyword argument 'filter'
I tried looking at the file which throws the error(map.py), but I realized quickly that there's just too much interaction in the files for me to grasp things quickly.
I hope the data I provided is sufficient for someone more familiar with kartograph than me to track the error down.
UPDATE: The error is still valid. I tested it on both a MacBook Pro and an Asus Netbook now(Arch and Bodhi Linux, respectively).
Thanks in advance,
Carson
As far as I know, you can solve that problem by including a 'bounds' parameter. It is in deed very tricky, because according to the documentation (is it valid to call it 'documentation') this error should not appear, since the only required parameter is 'layers'. Also, how the bounds are defined depend apparently from the chosen projection. For your example I would use a simple polygon bounds.
I also had problems with that error. But, after many trials to set up everything, I noticed that apparently it only appears in the command-line version of Kartograph, and not when using Kartograph as a Python module in a script. I.e., try to include the json dictionary into a Python script where you import kartograph, like in the example here below.
I also put an example of filtering, for the record, because it was another thing that failed to work when using the command-line version of Kartograph.
# file: makeMap.py
from kartograph import Kartograph
K = Kartograph()
def myfilter(record):
return record['iso_a3'] in ["FRA","ITA","DEU"]
config = {
"layers": {
"mylayer": {
"src": "ne_50m_admin_0_countries.shp",
"filter": myfilter,
"attributes": {"iso_a3":"iso_a3", "name":"name", "id":"iso_a3"}
}
},
}
K.generate(config, outfile='world.svg')
Then, run the script as a Python script:
python makeMap.py

JSON File Data Access Issue in Meteor?

I try to access to JSON file data using Meteor JS. But I'm unable to access it. Can anybody suggest what I'm doing wrong?
Folder Structure :
myapp project/lib folder - myfile.json
myfile.json:
EJSONObj = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "M",
"salary": 70000,
"registered": true,
"favorites":
{
"color": "Blue",
"sport": "Soccer",
"food": "Spaghetti"
}
}
Meteor JS :
if (Meteor.isClient)
{
console.log("My JSON File data:"+EJSONObj.age);
}
Error is :
Uncaught ReferenceError: EJSONObj is not defined
Meteor has recently introduced the private directory accompanied by an assets API.
The docs are at http://docs.meteor.com/#assets_getText and what it allows you to do is place your text and binary files in the private directory, they don't get served up to the client, and they are accessible to Meteor on the server side.
Since Meteor take all other JS and CSS resources and bundles them, the private directory is a place for other file types which you need to read and use.

Categories