Fetch json data from url and write in a file
jsondata
is a redundant variable. Here is a rewrite of your fetch().then().then()
which leverages fs.writeFile()
in the second .then()
.
I used node-fetch
for this implementation, but it should work in a browser environment as well.
fetch('http://somewebsite.null')
.then((response) => {
return response.json();
})
.then((json) => {
fs.writeFile('./test.json', JSON.stringify(json), (err) => {
if (err) {
throw new Error('Something went wrong.')
}
console.log('JSON written to file. Contents:');
console.log(fs.readFileSync('test.json', 'utf-8'))
})
})
Vanilla Javascript, how to read local JSON file
fetch()
returns a Promise
, so you don't need to create one yourself. Promise
returned by fetch
fulfills with a Response object on which you need to call .json() method to get the actual data. This method also returns a Promise
, so you need to chain another then()
method call.
fetch('./Data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
For details, see:- Using Fetch
How to fetch data from json file and display in html?
So I think you could do something like this:
Assuming you're html structure for the table looks like this:
<tr>
<td><input class="asset-tag" id='asset_tag_no${count}' type='text' onchange="getAssetInfo(this)" bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required description></textarea></td>
</tr>
Notice, I've added class
attributes to each input which we'll use later. Also, I updated the onChange to getAssetInfo(this)
which will pass the actual input element itself (instead of just the value).With this you can have a getAssetInfo
function like this
const getAssetInfo = (inputElement) => {
// get the asset tag id
const id = $(inputElement).val();
// get the table row that this input is in
const row = $(inputElement).closest("tr");
$.get(id, (data) => {
// find the `.description` element and set it's value
$(row).find("textarea.description").val(data.description);
// find the `.serial-no` element and set it's value
$(row).find("input.serial-no").val(data.manufacturer);
// ... add more finders and setters based on whatever else you're getting back from the data.
});
};
Once this is all set up, I think you'll find that it works.I didn't add all the input elements that you show in your example but hopefully you can figure out how to extend this to your needs.
Fetching local JSON
Try to use file system. Don't think reading from a JSON file works like that.
const fs = require('fs');
const json_data = require('../services/contributors.JSON');
fs.readFile(json_data, 'utf8', function (err, data) {
try {
data = JSON.parse(data)
for (let i in data){
console.log('Name:',data[i].name)
}
} catch (e) {
// Catch error in case file doesn't exist or isn't valid JSON
}
});
How to read an external local JSON file in JavaScript?
You cannot make a AJAX call to a local resource as the request is made using HTTP.
A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.
In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON()
:
http://api.jquery.com/jQuery.getJSON/
How to fetch data from a specific JSON file?
The response constains assets as an nested array. So you can use reduce and get all the elements in one array and then iterate it to create list
import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
const [todos, setTodos] = React.useState<any[]>([]);
React.useEffect(() => {
fetch(`https://web-coding-challenge.vercel.joyn.de/api/blocks`)
.then((results) => results.json())
.then((data) => {
const responseData = data.reduce((acc:any,curr:any)=>{
const assets = curr.assets;
acc.push(...assets)
return acc ;
},[])
setTodos(responseData);
});
}, []);
return (
<div className="App">
{todos.map((post: any) => (
<div>
<h1>{post.id}</h1>
<h2>{post.primaryImage.url}</h2>
</div>
))}
</div>
);
}
Fetching data from local json file
Tnx all for trying to help me, but my solution was putting .json file in public folder, and importing it in App.js... that Way engine didn't trow error and I resolved it with async/await.
Related Topics
Jquery Returning "Parsererror" for Ajax Request
Regular Expression for Ip Address Validation
What Are Some Empirical Technical Reasons Not to Use Jquery
If (Key in Object) or If(Object.Hasownproperty(Key)
Resize Jqgrid When Browser Is Resized
Why Does a Simple .*? Non-Greedy Regex Greedily Include Additional Characters Before a Match
JavaScript Array .Reduce with Async/Await
How to Get the Hue of a #Xxxxxx Colour
Mongoose, Select a Specific Field with Find
How to Export Socket.Io into Other Modules in Nodejs
Detect If an Element Is Visible with Jquery
Remove Whitespace and Line Breaks Between HTML Elements Using Jquery
How to Sum the Values of a JavaScript Object
Jquery Smooth Scroll to an Anchor
How to Parse a Date in Format "Yyyymmdd" in JavaScript