Loading Local Json File

Loading local JSON file

$.getJSON is asynchronous so you should do:

$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});

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/

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 read local json file in flutter

Here’s sample.json:

{
"items": [
{
"id": "p1",
"name": "Item 1",
"description": "Description 1"
},
{
"id": "p2",
"name": "Item 2",
"description": "Description 2"
},
{
"id": "p3",
"name": "Item 3",
"description": "Description 3"
}
]
}

The code which is used to fetch data from the JSON file (see the full code below):

Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
// ...
}

Declare the json file in the assets section in your pubspec.yaml file:

flutter:
assets:
- assets/sample.json

main.dart

import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter/services.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return const MaterialApp(
// Hide the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
List _items = [];

// Fetch content from the json file
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
setState(() {
_items = data["items"];
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
'Kindacode.com',
),
),
body: Padding(
padding: const EdgeInsets.all(25),
child: Column(
children: [
ElevatedButton(
child: const Text('Load Data'),
onPressed: readJson,
),

// Display the data loaded from sample.json
_items.isNotEmpty
? Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
leading: Text(_items[index]["id"]),
title: Text(_items[index]["name"]),
subtitle: Text(_items[index]["description"]),
),
);
},
),
)
: Container()
],
),
),
);
}
}

Load local JSON file into variable

If you pasted your object into content.json directly, it is invalid JSON. JSON keys and values must be wrapped in double quotes (" not ') unless the value is numeric, boolean, null, or composite (array or object). JSON cannot contain functions or undefined values. Below is your object as valid JSON.

{
"id": "whatever",
"name": "start",
"children": [
{
"id": "0.9685",
"name": " contents:queue"
},
{
"id": "0.79281",
"name": " contents:mqq_error"
}
]
}

You also had an extra }.

Load local JSON File into a HTML template

You can use fetch API to retrieve the informations of your JSON and if you use VSCode you can just launch the plugin Live Server to test it in your local directory.

  fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

Live Server Plugin for VSCode
https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer



Related Topics



Leave a reply



Submit