Display nested JSON data using Javascript - javascript

Afternoon all,
I'm trying to parse data from a nested json object.
For example: member.accuracy
Currently, it's returning the result undefined.
My code:
JSON (places.json):
{
"request_time": "2019-05-30T13:48:39+01:00",
"source": "Network Rail",
"acknowledgements": "Contains information of Network Rail Infrastructure Limited. License http://www.networkrail.co.uk/data-feeds/terms-and-conditions/",
"member": [
{
"type": "train_station",
"name": "London Euston",
"latitude": 51.528135,
"longitude": -0.133924,
"accuracy": 100,
"station_code": "EUS",
"tiploc_code": "EUSTON"
}
]
}
HTML:
<html>
<head>
<meta content="text/html; charset=utf-8">
<title>AJAX JSON by Javatpoint</title>
<script type="application/javascript">
function load()
{
var url = "http://myurl.places.json?";
var request;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();//for Chrome, mozilla etc
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only
}
request.onreadystatechange = function(){
if (request.readyState == 4 )
{
var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object
document.getElementById("date").innerHTML = jsonObj.request_time;
document.getElementById("time").innerHTML = jsonObj.member.accuracy;
}
}
request.open("GET", url, true);
request.send();
}
</script>
</head>
<body onload="load()">
Date: <span id="date"></span><br/>
Time: <span id="time"></span><br/>
</body>
</html>
Any help would be much appreciated!
Thanks,
Brad

As you can see in the json file, the member property holds an array, containing one object. To get accuracy, you must access it with an index:
var jsonObj = {
"member": [{
"type": "train_station",
"name": "London Euston",
"latitude": 51.528135,
"longitude": -0.133924,
"accuracy": 100,
"station_code": "EUS",
"tiploc_code": "EUSTON"
}]
}
console.log(jsonObj.member[0].accuracy)
Be aware that if you're fetching this data from some sort of API, there may be more than one object present in this array in future fetches, and the first element (index 0) may not be the one you're looking for.

Related

Parse non JSON to JSON

I have a file with data in it that I am needing to parse and store in a DB. Below, is an example of 2 entries in the file. I'm not quite sure what the structure is (although it looks to be ndJSON). I am trying to parse the data in to a JSON object in order to store it in a DB, but cannot seem to figure it out. Here is what I have so far
var ndjson = {
"sequence-num": "0123456789",
"version": "N1.4",
"record-type": "R",
"session-id": "197-30760303",
"date": "2021-07-23 15:00:53",
"passport-header": { "alg": "ES256", "ppt": "test", "typ": "passport", "x5u": "https://cr.com" },
"passport-payload": { "attest": "A", "dest": { "tn": ["0123456789"] }, "iat": 0123456789, "orig": { "tn": "0123456789" }, "origid": "c699f78a-ebc6-11eb-bfd8-bec0bbc98888" },
"identity-header": "eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiaHR0cHM6Ly9jci5zYW5zYXkuY29tL1RvdWNodG9uZV82ODNBIn0.eyJhdHRlc3QiOiJCIiwiZGVzdCI6eyJ0biI6WyIxMjUeyJhdHRlc3QiOiJCIiwiZGVzdCI6eyJ0biI6WyIxMj;info=<https://google.com/>;alg=ES256;ppt=\"test\""
}
{
"sequence-num": "0123456788",
"version": "N1.4",
"record-type": "R",
"session-id": "214-30760304",
"date": "2021-07-23 15:00:53",
"passport-header": { "alg": "ES256", "ppt": "test", "typ": "passport", "x5u": "https://cr.com" },
"passport-payload": { "attest": "B", "dest": { "tn": ["0123456788"] }, "iat": 0123456788, "orig": { "tn": "0123456788" }, "origid": "c69d0588-ebc6-11eb-bfd8-bec0bbc98888" },
"identity-header": "eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiaHR0cHM6Ly9jci5zYW5zYXkuY29tL1RvdWNodG9uZV82ODNBIn0.eyJhdHRlc3QiOiJCIiwiZGVzdCI6eyJ0biI6WyIxMjUeyJhdHRlc3QiOiJCIiwiZGVzdCI6eyJ0biI6WyIxMj;info=<https://google.com/>;alg=ES256;ppt=\"test\""
};
let result = ndjson.split(',').map(s => JSON.parse(s));
console.log('The resulting array of items:');
console.log(result);
console.log('Each item at a time:');
for (o of result) {
console.log("item:", o);
}
When I run this, I get Uncaught SyntaxError: Unexpected token ':' error on line 12 at the 2nd node of "sequence-num": "0123456788",.
Any help is appreciated, thank you!
If you actually have ndJSON(newline-delimited JSON) then each line in the file is valid JSON, delimited by newlines. A simple file would look like this:
{"key1": "Value 1","key2": "Value 2","key3": "Value 3","key4": "Value 4"}
{"key1": "Value 5","key2": "Value 6","key3": "Value 7","key4": "Value 8"}
This differs from the formatted data you've posted here, and the difference is important since once you've formatted it, the valid JSON objects cannot simply be distinguished by the presence of newlines.
So, on the assumption that you do have valid ndJSON, in its original form, you can extract it by using split() on newLines and using JSON.parse() on the resulting array.
This snippet adds a little file handling to allow a file to be uploaded, but thereafter it uses split() and JSON.parse() to extract the data:
"use strict";
document.getElementsByTagName('form')[0].addEventListener('submit',function(e){
e.preventDefault();
const selectedFile = document.getElementById('inputFile').files[0];
let fr = new FileReader();
fr.onload = function(e){
let ndJSON = e.target.result; // ndJSON extracted here
let ndJSONLines = ndJSON.split('\n');
// Process JSON objects here
ndJSONLines.forEach(function(el){
let obj = JSON.parse(el);
Object.keys(obj).forEach(key=>{
console.log(`Key: ${key}, Value: ${obj[key]}`);
});
});
}
fr.readAsText(selectedFile)
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Parsing ndJSON</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="inputFile" id="inputFile">
<input type="submit">
</form>
</body>
</html>
Output, based on the sample file above:
Here is what I do
const end_point_url = 'https://ipfs.io/ipfs/bafkqap33ejwgs3tfgerduitomrvhg33oebtg64tnmf2c4lroej6qu6zcnruw4zjsei5ce5dinfzsa2ltebqsa43fmnxw4zbanruw4zjcpufa';
let json = await fetch(end_point_url).
then( resp => resp.text() ).
then( buf => { // NDJSON format ...
return buf.slice(0,-1).split('\n').map(JSON.parse);
}).
catch(console.error);

Parsing JavaScript MySQL response

Am reading MySQL via javascript,
and am getting response back successfully and returning data
But my question is that how can i parse and get only
whats your first school
from this output
{
"Success": true,
"Result": [
{
"question": "whats your first school"
}
]
}
<html>
<head>
<title>MySqlJs test</title>
</head>
<script src="http://mysqljs.com/mysql.js"></script>
<body>
<pre id="output"></pre>
<script>
MySql.Execute(
"host",
"serv",
"pwd",
"db56",
"select quest from datab",
function (data) {
document.getElementById("output").innerHTML = JSON.stringify(data,null,2);
});
</script>
</body>
</html>
Assuming data is a JavaScript object (If it's a string use JSON.parse()) you can access it like:
const data = {
"Success": true,
"Result": [{
"question": "whats your first school"
}]
}
console.log(data.Result[0].question);

Using js to call rest API and execute a post

I created 3 files (html, js and php) to call a restAPI from the js. But it is not working and I found zero clue on the web. It just does not work
Step 1 - HTML - for now, I use it to call the js script at the click on the button in this first moment I just try to call the js with the rest calling.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>
Web 2 Case - Abertura de Chamados
</title>
</head>
<body style="text-align:center;" id="body">
<!-- Button to send data -->
<button onclick="sendJSON()">Send JSON</button>
<!-- For printing result from server -->
<p class="result" style="color:green">
2 - Then I have index.js
function sendJSON(){
let result = document.querySelector('.result');
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "**The endpoint url**";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
xht.setRequestHeader("Authorization","00Df0000003dGUH!AQUAQLpQJlcqfKpqZUW9KZjwubQi4YcV7IrfZrw_Y53X_adKMCBHVXzblySCHtYfwO5YLh1EBcUTrX7qxp9EkSjhKvBfzl4M");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify({"Fields":["requestDefinitionId": "a3Hf0000000lTNaEAM", "client": "0053j00000A7rWLAAZ"],["Answers":{"a3Df0000000qI63EAE":[ "Reclamação" ],"a3Df0000000qHvsEAE":[ "Solicitação de Serviço aberta por qualquer integração web","a3Df0000000qHwREAU":["Web"] ]}]});
// Sending data with the request
xhr.send(data);
}
I believe that my var data is not good. When I call the endpoint from postman, I wrote the body
{
"Fields": [
{
"Name": "requestDefinitionId",
"Value": "a3Hf0000000lTNaEAM"
},
{
"Name": "client",
"Value": "0053j00000A7rWLAAZ"
}
],
"Answers": [
{
"QuestionId": "a3Df0000000qI63EAE",
"Values": [ "Reclamação" ]
},
{
"QuestionId": "a3Df0000000qHvsEAE",
"Values": [ "Solicitação de Serviço aberta por qualquer integração web" ]
},
{
"QuestionId": "a3Df0000000qHwREAU",
"Values": ["Web"]
}
]
}
illustrating the body I paste above
If you copy the contents of the JSON.stringify() argument into this validator, https://jsonformatter.curiousconcept.com/#, you will see that the "Fields" array is not formatted correctly; I think you want it's contents to be an object within curly brackets. So that would be why index.js does not work correctly.

I am not get value which is sent in request body in specific json format

I need help in my one issue. I have write the program in that I am use map in node.js.
I am testing this program using postman by sending JSON structure, however I am not get specific value in console which I am printing.
Please see below code .
async CreateProduceMVPRateAsset(data, callback) {
// Create a new file system based wallet for managing identities.
var ProducePRICE = {};
var MVPRATE = new Map();
var MVPPRICE =[];
var MVPPRICE_BS ={};
var MVPPRICE_LB ={};
var PRODUCENAME = data.PRODUCE
console.log('PRODUCENAME', PRODUCENAME);
var COUNTRY = data.COUNTRY;
console.log('COUNTRY', COUNTRY);
var STATE = data.STATE;
console.log('STATE', STATE);
MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', MVPRATES); // not getting value of MVPRATES from request body
}
JSON structure which is sending using POSTMAN
{
"username": "admin2",
"PRODUCE": "Apple",
"STATE": "MI",
"COUNTRY": "US",
"MVPRATES": {
"fuji": {
"VARIETY": "fuji",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
},
"gala": {
"VARIETY": "gala",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
}
}
}
output
Any help very appreciable
Thanks
Abhijeet
That's how logs will show up for the non-primitive type of data. Try stringifying the response like:
MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', JSON.stringify(MVPRATES));
This will help you in printing actual values to the logs. A better approach will be to use a logging module like winston and configure all such things and many more.
Sorry to waste you all time I think I miss the var in front of MVPRATES. It should be
var MVPRATES = data.MVPRATES;

Get Json Array with pure JS

I would like to get JSON Array from a cross domain without using JQuery. The data from cross domain is like this:
{
"transactionid": "LBS_48550801",
"status": 0,
"countrylist":
[
{ "id": 1, "name": "France", "latitude": 37.00039, "longitude": 35.31411, "extent": { "minlatitude": 36.53888499, "minlongitude": 34.76786904, "maxlatitude": 38.37851496, "maxlongitude": 36.40534884 }},
{ "id": 2, "name": "Germany", "latitude": 37.76454, "longitude": 38.27645, "extent": { "minlatitude": 37.40771898, "minlongitude": 37.43326512, "maxlatitude": 38.21203404, "maxlongitude": 39.24767592 } },
//... .... ....
//... .... ....
//... .... ....
{ "id": 98, "name": "Belgium", "latitude": 38.75754, "longitude": 30.5387, "extent": { "minlatitude": 37.78126803, "minlongitude": 29.68963308, "maxlatitude": 39.27915099, "maxlongitude": 31.71549708 } },
{ "id": 99, "name": "England", "latitude": 39.71812, "longitude": 43.03345, "extent": { "minlatitude": 38.96877501, "minlongitude": 42.28340184, "maxlatitude": 40.031208, "maxlongitude": 44.61092892 } },
]
}
After getting the data, I need to parse it to get "countrylist" list.
I searched for solving this issue but the examples are all with JQuery. I dont want to use it. As you see, I have transactionid, status parameters in the input. So, after importing the data, I need to parse it to get the countrylist array. I know how to parse it, but I couldnt get the whole data from the service.
I need to get the data by Javascript methods. The server supports retrieving data well.
The steps to be taken are:
1- Get the whole data (Here is where I got stuck)
2- Parse it as Json Object (I know how to parse the data)
How can I get the whole data without using any JQuery or other prepared libraries?
You can use XMLHttpRequest for ajax and JSON.parse for parse json :)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '//example.org', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
var countryList = obj.countrylist;
}
}
};
xmlhttp.send(null);
You should never use eval! Eval is evil! You can read about it on mdn
UPD:
If there is no CORS header, you can use JSONP. Just add &callback=getJSONP to your URL. Try it on jsfiddle: http://jsfiddle.net/VmBF7/3/
since your operation involving cross domain requests, i suggest you to use jsonp request.
this question has what you wanted.
Could you try to download the data to a hidden iframe and then parse the content of its document.body?
In my case, since the server require a ajax request or it will give you a 404(to prevent csrf), so based on what the accepted answer, you need one extra line to complete the getJSON ajax version like this:
<script type="application/javascript">
var request = new XMLHttpRequest();
request.open('GET', '/your/url', true);
// this following line is needed to tell the server this is a ajax request
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
var json = JSON.parse(this.response);
// this is where you can do something with the json response
}
};
request.send();
});
</script>

Categories