I am just trying to load JSON file into my react project. I did it like this:
fetch(dane).then(response => {
console.log(response);
return response.json();
}).then(dane => {
console.log(dane);
}).catch(err => {
console.log("Error Reading data " + err);
});
and I imported this file into project:
import data from "./data.json";
but I am getting error like this:Unexpected token < in JSON at position 0
How can I fix it?
If I am asking about something very stupid, just sorry.
The json file is in src folder.
You would only use fetch to get the data from an API and assign the response to a variable that you can call.
Since you are using a mock json response stored in a file, you can do the following.
Example:
A file called data.json containing the following.
{
"name": "John",
"age": "47",
"role": "admin"
}
Can be imported via:
import data from "./data.json"
Then used in your component however you wish.
<h1>Hello {data.name}.</h1>
<h2>Logged in as: {data.role}</h2>
Or if used outside of the render, like in a function:
console.log(data.role)
Also, Unexpected token < in JSON at position 0 seems like your JSON is improperly formatted.
The JSON file should only contain valid JSON data, as shown in my basic example above.
Related
Let's say that I have a JSON file called data.json in Github. I can view it in raw in a Github URL like this: https://raw.githubusercontent.com/data.json (This is a hypothetical URL. It's not real)
And let's say that URL contains JSON data like this:
"users_1": [
{
"id": 1234,
"name": "Bob"
},
{
"id": 5678,
"name": "Alice"
}
]
How do I extract the whole JSON data from that URL and store it in a variable in a Cypress test? I know that Cypress doesn't really use Promises, so I'm finding it difficult to implement this. So far I got this in Typescript:
let users; // I want this variable to store JSON data from the URL
const dataUrl = "https://raw.githubusercontent.com/data.json";
cy.request(dataUrl).then((response) => {
users = JSON.parse(response); // This errors out because response is type Cypress.Response<any>
})
I'm planning to do something like this in the future for my project when migrating from Protractor to Cypress. I have a Protractor test that extracts JSON data from a Github file and stores it a variable by using a Promise. I want to do the same kind of task with Cypress.
I think you should use response.body, and it should have been serialized.
A request body to be sent in the request. Cypress sets the Accepts request header and serializes the response body by the encoding option. (https://docs.cypress.io/api/commands/request#Usage)
I am using Axios to load a static JSON from the React application server, and upon reading the files, there are many key/value pairs missing.
The JSON file in question is asset-manifest.json, which includes all the assets (media, css, js) files in the app, and is generated in the build process by webpack. I use this file as reference to pre-load the images for the website.
The JSON file looks like this (ellipsis added by me, ofc):
{
"files": {
"main.js": "/static/js/main.04cbf801.chunk.js",
"main.js.map": "/static/js/main.04cbf801.chunk.js.map",
"runtime-main.js": "/static/js/runtime-main.ed6fc4d3.js",
"runtime-main.js.map": "/static/js/runtime-main.ed6fc4d3.js.map",
"static/css/2.f5a05697.chunk.css": "/static/css/2.f5a05697.chunk.css",
"static/js/2.448c4959.chunk.js": "/static/js/2.448c4959.chunk.js",
"static/js/2.448c4959.chunk.js.map": "/static/js/2.448c4959.chunk.js.map",
"static/css/3.d7d661be.chunk.css": "/static/css/3.d7d661be.chunk.css",
"static/js/3.1605bce2.chunk.js": "/static/js/3.1605bce2.chunk.js",
"static/js/3.1605bce2.chunk.js.map": "/static/js/3.1605bce2.chunk.js.map",
"index.html": "/index.html",
"precache-manifest.093a3239b1d438e30c3887d109b2e7b2.js": "/precache-manifest.093a3239b1d438e30c3887d109b2e7b2.js",
"service-worker.js": "/service-worker.js",
"static/css/2.f5a05697.chunk.css.map": "/static/css/2.f5a05697.chunk.css.map",
"static/css/3.d7d661be.chunk.css.map": "/static/css/3.d7d661be.chunk.css.map",
"static/media/ANKLES.6d795be0.svg": "/static/media/ANKLES.6d795be0.svg",
"static/media/ARMS.8418bd6e.svg": "/static/media/ARMS.8418bd6e.svg",
(...)
},
(...)
}
And there is nothing extraordinary in the key/value pairs that are missing. In total, these are about 15 missing entries, from a total of more than 400. For example, these are some of the key/value pairs missing:
"static/media/testa.png": "/static/media/testa.0b92a7e4.png",
"static/media/Osso01.png": "/static/media/Osso01.9949a55e.png",
"static/media/CabeloHomem01.png": "/static/media/CabeloHomem01.258b6c19.png"
This is the code I am using to load the JSON:
axios.get("asset-manifest.json")
.then(manifest => {
// entries in manifest are already missing at this point
// do stuff with manifest
})
I tried using fetch instead of Axios, for the same result.
BTW, if I copy the JSON code and parse it in the console/terminal, all entries are parsed as expected.
As a workaround, I can embed the related images in the code using base 64, but that's a last resort that I'd prefer to avoid.
Any ideas?
Thanks for reading.
is working fine with fetch first check your response in the postman or any other that you like
let payload = {
token: 'p1ztA-3ZEYrX2wJAa_juSg',
data: {
'static/media/testa.png': '/static/media/testa.0b92a7e4.png',
'static/media/Osso01.png': '/static/media/Osso01.9949a55e.png',
'static/media/CabeloHomem01.png':
'/static/media/CabeloHomem01.258b6c19.png',
'main.js': '/static/js/main.04cbf801.chunk.js',
'main.js.map': '/static/js/main.04cbf801.chunk.js.map',
'runtime-main.js': '/static/js/runtime-main.ed6fc4d3.js',
'runtime-main.js.map': '/static/js/runtime-main.ed6fc4d3.js.map',
'static/css/2.f5a05697.chunk.css': '/static/css/2.f5a05697.chunk.css',
'static/js/2.448c4959.chunk.js': '/static/js/2.448c4959.chunk.js',
'static/js/2.448c4959.chunk.js.map': '/static/js/2.448c4959.chunk.js.map',
'static/css/3.d7d661be.chunk.css': '/static/css/3.d7d661be.chunk.css',
'static/js/3.1605bce2.chunk.js': '/static/js/3.1605bce2.chunk.js',
'static/js/3.1605bce2.chunk.js.map': '/static/js/3.1605bce2.chunk.js.map',
'index.html': '/index.html',
'precache-manifest.093a3239b1d438e30c3887d109b2e7b2.js':
'/precache-manifest.093a3239b1d438e30c3887d109b2e7b2.js',
'service-worker.js': '/service-worker.js',
'static/css/2.f5a05697.chunk.css.map':
'/static/css/2.f5a05697.chunk.css.map',
'static/css/3.d7d661be.chunk.css.map':
'/static/css/3.d7d661be.chunk.css.map',
'static/media/ANKLES.6d795be0.svg': '/static/media/ANKLES.6d795be0.svg',
'static/media/ARMS.8418bd6e.svg': '/static/media/ARMS.8418bd6e.svg',
},
};
fetch('https://app.fakejson.com/q', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(response => response.json())
.then(json => console.log(json));
I have a basic Angular web app which reads from a JSON file located on the same server as the app and parses through the JSON file in order to set certain values on objects which drive certain behavior in my app (applies css classes, etc.)
I am not able to find online and/or figure out myself how to set up the controller to read from the JSON file in a way that allows the file to be changed and Angular to dynamically reload the file once it has been changed without reloading the entire page. The JSON file is local on the server where the app is deployed, and I wanted to avoid standing up a web service just to serve a file that already exists on the same server the app is deployed.
Here is what I am doing now:
ngOnInit(): void {
// Make the HTTP request:
this.http.get('../assets/applicationLogs.json').subscribe(data => {
// Read the result field from the JSON response.
this.node_a_status= data.nodes[0].status;
this.node_b_status= data.nodes[1].status;
this.node_c_status= data.nodes[2].status;
});
}
And here is a what my JSON file looks like:
{
"nodes":[
{ "node":"Node A", "status":"processing", "errors":null },
{ "node":"Node B", "status":"processing", "errors":null },
{ "node":"Node C", "status":"inactive", "errors":null }
]
}
First, I know I will probably need to move this get logic out of ngOnInit(), but I am a little lost on how I should go about achieving the desired behavior I have described with typescript.
You're using an http request method on the file so "Poll it"... same way you would any other http JSON service. Here's a ready made poller for you to import: https://www.npmjs.com/package/rx-polling
Best thing you can do is create a service out of it and call it in ngOnInit method and use the response the same way you've shown.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/dom/ajax';
import 'rxjs/add/operator/map';
import polling from 'rx-polling';
// Example of an Observable which requests some JSON data
const request$ = Observable.ajax({
url: '../assets/applicationLogs.json',
crossDomain: true
}).map(response => response.response || [])
.map(response => response.slice(0, 10)); // Take only first 10 comments
polling(request$, { interval: 5000 }).subscribe((comments) => {
console.log(comments);
}, (error) => {
// The Observable will throw if it's not able to recover after N attempts
// By default it will attempts 9 times with exponential delay between each other.
console.error(error);
});
I am trying to figure out how to plot data from a local '.JSON' file using angular2-highcharts example.
I followed the example in 'https://www.npmjs.com/package/angular2-highcharts' to first understand how to plot .JSON data and it worked. I took the data available for the example and created a local .JSON file (copied the content from 'https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK' in notepad and saved it with UTF-8 encoding as a .JSON file), and replaced the file path for the JSON request to this. When I do this though, I get an error - response with status 200.
constructor(jsonp : Jsonp) {
//jsonp.get('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK').subscribe(res => {
jsonp.get('./data.json').subscribe(res => {
this.options = {
title : { text : 'AAPL Stock Price' },
series : [{
name : 'AAPL',
data : res.json(),
tooltip: {
valueDecimals: 2
}
}]
};
});
}
options: Object;
};
Since I am not super familiar with json data/ Javascript or angular2 I am not sure if I am missing something very basic here. Any help is appreciated.
as far as I know, Response Status 200 specifies that request was successful. i.e. your request was successfully handled. perhaps you want to try checking response data.
check your callback for response data.
Using http instead of json helped. I made use of the suggestion in this answer https://stackoverflow.com/a/36305814/4567096.
I just started learning nodejs. I am currently working with sockets and made chat program.
I want to save entire chat to a json file. Currently my code is this :
socket.on('chat', function (data) {
message = {user : data.message.user, message : data.message.message};
chat_room.sockets.emit('chat', {message: message});
jsonString = JSON.stringify(message);
fs.appendFile("public/chat.json", jsonString, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
This is currently working perfect, but the json which is written in file is wrong.
This gave me a wrong json
{"user":"niraj","message":"hw r u?"}{"user":"ntechi","message":"hello"}{"user":"ntechi","message":"hw r u?"}
The above code is called when message is triggered. I want json in this format
{"user":"awd","message":"hw r u?","user":"ntechi","message":"hello","user":"ntechi","message":"hw r u?"}
Can anyone help me in this? Thanks in advance
The first set of wrong JSON is created because you are appending a piece of JSON to a file each time you get a message.
The second set of JSON is also wrong - each property name has to be unique.
Presumably you want something like:
[
{"user":"niraj","message":"hw r u?"},
{"user":"ntechi","message":"hello"},
{"user":"ntechi","message":"hw r u?"}
]
In which case the logic you need to use is:
Read data from file
Parse data as JSON and assign to a variable
In the event of an error, assign an empty array to that variable
push the message object onto the end of the array
stringify the array
Overwrite the file with the new string