I tried to import a JSON file in my React project, but got the parsing error:
json file:testData.json
{
"data": {
"articles": [
{
"id": "95c12a8f6c88953ca8f8a39da25546e6",
"title": "Introducing React's Error Code System",
"date": "Mon Jul 11 2016 00:00:00 GMT+0000 (UTC)",
"authorId": "2c6aa2cfe3449467d329fa17d6ea230f",
"body": "Building a better developer experience has been one of the things that React deeply cares about, and a crucial part of it is to detect anti-patterns/potential errors early and provide helpful error messages when things (may) go wrong. However, most of these only exist in development mode; in production, we avoid having extra expensive assertions and sending down full error messages in order to reduce the number of bytes sent over the wire."
}
],
"authors": [
{
"id": "d85577ea34ae50f2dac5347b5219aa23",
"firstName": "Andrew",
"lastName": "Clark",
"website": "https://twitter.com/acdlite"
}
]
}
}
DataApi.js file:
export default class DataApi {
// property: rawData
constructor(rawData) {
this.rawData = rawData;
}
mapIntoObject(arr) {
return arr.reduce((acc, curr) => {
acc[curr.id] = curr;
return acc;
}, {});
}
getArticle() {
return this.mapIntoObject(this.rawData.articles);
}
getAuthors() {
return this.mapIntoObject(this.rawData.authors);
}
}
And I tried to import JSON data in this file:
import DataApi from "./DataApi"; // object to process data
import { data } from "./testData.json"; // raw data
// create a api object to host raw data
let api = new DataApi(data);
const articles = api.getArticle();
console.log(articles);
then I got the error:(the import directory are correct):
2:13 error Parsing error: Unexpected token, expected ";"
1 | {
> 2 | "articles": [
| ^
3 | {
4 | "id": "95c12a8f6c88953ca8f8a39da25546e6",
5 | "title": "Introducing React's Error Code System",
What is the problem?
You can do export default
testData.json:
const data = {
"data": {
"articles": [
{
"id": "95c12a8f6c88953ca8f8a39da25546e6",
"title": "Introducing React's Error Code System",
"date": "Mon Jul 11 2016 00:00:00 GMT+0000 (UTC)",
"authorId": "2c6aa2cfe3449467d329fa17d6ea230f",
"body": "Building a better developer experience has been one of the things that React deeply cares about, and a crucial part of it is to detect anti-patterns/potential errors early and provide helpful error messages when things (may) go wrong. However, most of these only exist in development mode; in production, we avoid having extra expensive assertions and sending down full error messages in order to reduce the number of bytes sent over the wire."
}
],
"authors": [
{
"id": "d85577ea34ae50f2dac5347b5219aa23",
"firstName": "Andrew",
"lastName": "Clark",
"website": "https://twitter.com/acdlite"
}
]
}
}
export default data;
and while importing
With json-loader installed, you can use
import data from "./testData.json";
or If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:
import data from "./testData";
To install json-loader
npm install --save-dev json-loader
And add below config to your webpack.config.js
webpack.config.js
module.exports = {
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
}
]
}
}
You have to export your json data, your json data should be like this.
export const data = {
"data": {
"articles": [
{
"id": "95c12a8f6c88953ca8f8a39da25546e6",
"title": "Introducing React's Error Code System",
"date": "Mon Jul 11 2016 00:00:00 GMT+0000 (UTC)",
"authorId": "2c6aa2cfe3449467d329fa17d6ea230f",
"body": "Building a better developer experience has been one of the things that React deeply cares about, and a crucial part of it is to detect anti-patterns/potential errors early and provide helpful error messages when things (may) go wrong. However, most of these only exist in development mode; in production, we avoid having extra expensive assertions and sending down full error messages in order to reduce the number of bytes sent over the wire."
}
],
"authors": [
{
"id": "d85577ea34ae50f2dac5347b5219aa23",
"firstName": "Andrew",
"lastName": "Clark",
"website": "https://twitter.com/acdlite"
}
]
}
}
change .json to .js extention, while importing
import { data } from "./testData"; // raw data
Related
I have posted a bulk import with a file containing group transaction bundles in ndjson format. After posting I see them to be stored as bundles itself in the FHIR store instead of individual resources. But according to documentation when we store data as transaction bundle the resources inside that bundle should be created individually, but the records are getting created as a bundle itself.
I am using following import body, let me know if any changes are to be done for the body
How to post transaction bundle using $import?
{
"resourceType": "Parameters",
"parameter": [
{
"name": "inputFormat",
"valueString": "application/fhir+ndjson"
},
{
"name": "mode",
"valueString": "InitialLoad"
},
{
"name": "input",
"part": [
{
"name": "type",
"valueString": "Bundle"
},
{
"name": "url",
"valueUri": "https:xyz/fhir-sample-import-data/patient_bundles_ndjson.ndjson"
}
]
}
]
}
Decided to find out what all the fuss was about with Angular. Got a demo app working with a JSON file (using db.json and JSON server from the angular CLI). All working great.
So I get adventurous and decide to build a C# API (as that's the long plan anyway).
Straight away I ran into the CORS problem, and to solve in my ASP.NET config I have (startup.cs)
app.UseCors( options =>
{
options
.WithOrigins("http://localhost:4200/")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
I output my JSON like this (done this like a thousand times in all my apps)
return Json(new { tasks = _context.Tasks });
In my angular app, I have
//private apiUrl = 'http://localhost:5101/tasks'; //<- this is using json server
private apiUrl = "https://localhost:44363/home/tasks"; //<- this is my asp.net api
constructor(private http: HttpClient) {}
getTasks(): Observable<Task[]> {
return this.http.get<Task[]>(this.apiUrl);
}
My web service spits out the exact same JSON (char for char) as the JSON server but in my browser console (after dealing with the cors problem ) I get this:
ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
I've read lots of articles on here about this error but non seem to deal with this situation, (none that I could find anyway) and I checked a fair few
What am I missing?
This is the JSON
{
"tasks": [
{
"id": 1,
"text": "Doctors Appointment",
"day": "1st January 2022 at 10:30 AM",
"reminder": false
},
{
"id": 2,
"text": "Meeting",
"day": "5th July 2022 at 11:45 AM",
"reminder": false
},
{
"id": 3,
"text": "Car Servicing",
"day": "15th October 2022 at 8:30 AM",
"reminder": false
},
{
"id": 4,
"text": "Cleaner",
"day": "3rd November 2022 at 10:00 AM",
"reminder": false
},
{
"id": 5,
"text": "Dinner",
"day": "6th July 2022 at 7:50 PM",
"reminder": false
}
]
}
Based on your JSON, HttpGet expects to receive the data model as below:
export interface TaskResponse {
tasks: Task[];
}
And with .pipe(map) to return response.tasks as Observable<Task[]>.
import { map } from 'rxjs/operators';
getTasks(): Observable<Task[]> {
return this.http
.get<TaskResponse>(this.apiUrl)
.pipe(map((response: TaskResponse) => response.tasks));
}
Sample Demo on StackBlitz
This error is just because you are trying to loop an object. Just take the data into a result like
this.getTasks().subscribe(result => {
this.data = result.tasks;
})
After taking the response in data you can use the loop.
I found problem when using custom routes for requesting db.json which is deployed in json-server.
For example for this given json as below, I'd like to access voters by name, so when I type this
url:
https://localhost:3000/data/1/sessions/:sessionId/voters/:voterName
Where are sessionId and voterName are parameterized, the response should be {"voterName"}
db.json:
{
"id": 1,
"name": "Angular Connect",
"date": "2036-09-25T23:00:00.000Z",
"time": "10:00 am",
"price": 599.99,
"imageUrl": "/assets/images/angularconnect-shield.png",
"location": {
"address": "1057 DT",
"city": "London",
"country": "England"
},
"sessions": [
{
"id": 1,
"name": "Using Angular 4 Pipes",
"presenter": "Peter Bacon Darwin",
"duration": 1,
"level": "Intermediate",
"abstract": "Learn all about the new pipes in Angular 4, both \n how to write them, and how to get the new AI CLI to write \n them for you. Given by the famous PBD, president of Angular \n University (formerly Oxford University)",
"voters": [
"bradgreen",
"igorminar",
"martinfowler"
]
},
{
"id": 2,
"name": "Getting the most out of your dev team",
"presenter": "Jeff Cross",
"duration": 1,
"level": "Intermediate",
"abstract": "We all know that our dev teams work hard, but with \n the right management they can be even more productive, without \n overworking them. In this session I'll show you how to get the \n best results from the talent you already have on staff.",
"voters": [
"johnpapa",
"bradgreen",
"igorminar",
"martinfowler"
]
},
{
"id": 3,
"name": "Angular 4 Performance Metrics",
"presenter": "Rob Wormald",
"duration": 2,
"level": "Advanced",
"abstract": "Angular 4 Performance is hot. In this session, we'll see \n how Angular gets such great performance by preloading data on \n your users devices before they even hit your site using the \n new predictive algorithms and thought reading software \n built into Angular 4.",
"voters": []
},
{
"id": 4,
"name": "Angular 5 Look Ahead",
"presenter": "Brad Green",
"duration": 2,
"level": "Advanced",
"abstract": "Even though Angular 5 is still 6 years away, we all want \n to know all about it so that we can spend endless hours in meetings \n debating if we should use Angular 4 or not. This talk will look at \n Angular 6 even though no code has yet been written for it. We'll \n look at what it might do, and how to convince your manager to \n hold off on any new apps until it's released",
"voters": []
},
{
"id": 5,
"name": "Basics of Angular 4",
"presenter": "John Papa",
"duration": 2,
"level": "Beginner",
"abstract": "It's time to learn the basics of Angular 4. This talk \n will give you everything you need to know about Angular 4 to \n get started with it today and be building UI's for your self \n driving cars and butler-bots in no time.",
"voters": [
"bradgreen",
"igorminar"
]
}
]
}
For showing the last result I used custom routes in NodeJS like below:
router.js:
var jsonServer = require('json-server')
const low = require('lowdb')
var server = jsonServer.create()
const db = low('db.json')
// Add custom routes before JSON Server router
server.get('/data/:id/sessions/:sessionId/voters/:voterName', function (req, res) {
// See https://github.com/typicode/lowdb
var user=db.get("sessions")
.find({id:sessionId})
.get("voters")
.find({voterName})
.value()
if (user) {
res.jsonp(user)
} else {
res.sendStatus(404)
}
})
server.use(function (req, res, next) {
if (req.method === 'POST') {
req.body.createdAt = Date.now()
}
// Continue to JSON Server router
next()
})
// Use default router
// server.use(router)
server.listen(3000, function () {
console.log('JSON Server is running')
})
But when I run this command:
json-server --watch db.json --middlewares router.js
I get the following error:
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\node_modules\express\lib\application.js:210:11)
at createApp (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:79:9)
at load (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:148:13)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\utils\load.js:37:5)
at start (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:125:5)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\run.js:162:3)
at module.exports (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\index.js:81:3)
at Object.<anonymous> (C:\Users\maoutir\AppData\Roaming\npm\node_modules\json-server\lib\cli\bin.js:3:14)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
Thanks in advance for your answer.
I think you should not use the --middlewares options to start your server, router.js is not a middleware. so here it try to add your router.js as a middleware and fail to start
could you try :
json-server router.js --watch db.json
There are two options to use json server one is running it through your own js file the other is through running the middle wares you are running the js file you should be running middlewares as such https://github.com/typicode/json-server#add-middlewares only create the module.export as shown in the link. You don't need all the fancy server stuff.
I am working on a IVR solution for small businesses in my local area but I am having trouble wrapping my head around how Node will handle menus. I could make a seperate Node server for each of my customers but I would like to have a single server that pulls each customer's IVR setup from a Mongo database or file when their number is called. I have an idea on how to save the menu structure in JSON but I am lost when it comes to turning that JSON into responses to <gather> inputs. I was thinking I could use a JSON structure like this in the DB (or maybe as a .json file on Amazon S3):
{
"menu": {
"id": 1,
"name": "Main",
"script": "Thank you for calling Local Company. To speak to sales press 1, ...",
"options": [
{
"name": "",
"action": "",
"value": "",
"next": ""
},
{
"name": "Sales",
"action": "dial",
"value": 12345678901,
"next": ""
},
{
"name": "Support",
"action": "dial",
"value": 12345678902,
"next": ""
},
{
"name": "Directions",
"action": "say",
"value": "Our offices are located at...",
"next": 1
},
{
"name": "Mailbox",
"action": "mailbox",
"value": "main",
"next": 1
}
]
}
}
Twilio developer evangelist here.
If you can return the JSON based on the number a user is dialling, then you could do something like this:
const Twilio = require('twilio');
app.post('/voice', (req, res) => {
const dialledNumber = req.body.To;
getIVRObjectFromPhoneNumber(dialledNumber, (IVRObject) => {
const twiml = Twilio.twiml.VoiceResponse();
if (typeof req.body.Digits !== 'undefined') {
// A user has pressed a digit, do the next thing!
const action = IVRObject.menu.options[req.body.Digits]
twiml[action.action](action.value);
} else {
// No digits yet, return the <Gather>
const gather = twiml.gather({
numDigits: 1
});
gather.say(IVRObject.script);
}
res.send(twiml.toString());
});
});
This doesn't quite use all of your object, I'm not sure what the values for next mean, but hopefully it's a start. The getIVRObjectFromPhoneNumber method is my made up, asynchronous method that returns a JavaScript object parsed from your example JSON above.
Let me know if this helps at all.
I am trying to generate an access code using the script
https://raw.githubusercontent.com/fgalan/oauth2-example-orion-client/master/token_script.sh
I believe the response json has changed and the sed pattern is not working anymore.
How can I generate a valid access token?
Json response:
{
"access": {
"token": {
"issued_at": "2015-05-12T14:29:03.523315",
"expires": "2015-05-12T15:29:03Z",
"id": "?????",
"audit_ids": [
"????"
]
},
"serviceCatalog": [],
"user": {
"username": "pedro#viur.pt",
"roles_links": [],
"id": "pedro-almeida",
"roles": [],
"name": "pedro#viur.pt"
},
"metadata": {
"is_admin": 0,
"roles": []
}
}
}
line that generates the token
TOKEN=`echo $RESP | sed "s/{\"access\":{\"token\":{.*\"id\":\"\(.*\)\"},\"user.*$/\1/g"`
I have tried to use the access:token:id returned but it does not work.
The new id is also shorter then the old ones
Thanks
This problem was caused by the IdM migration at FIWARE Lab in early May 2015. After be aware of it, the PEP at orion.lag.fiware.org and token generation script have been fixed.
Please, donwload again the token_script.sh file and try again. It should work.