Parsing JavaScript MySQL response - javascript

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);

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);

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.

Javascript / Json / Firestore code to firestore bulk upload

We are looking for ways to bulk upload data into google firestore and found here in Stack Overflow an awesome script to do so, sort of. The problem is that when data is uploaded the collection is fine, document is fine, but nesting some data we can only manage to import as "map" type when we need "array" and "map". Since we are basically newbies trial and error has not been enough. We appreciate if you can take a look at the code and help us with that.
So far, with the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-firestore.js"></script>
</head>
<body>
<script>
var config = {
apiKey: 'MY API KEY',
authDomain: 'MY AUTHDOMAIN',
projectId: 'MY PROJECT ID'
};
firebase.initializeApp(config);
var firestore = firebase.firestore();
//Paste from the CSV to JSON converter
const data = [
{
"collection": "sub_cats",
"uid": "Av9vJ0EoFfxhAR2",
"class": "especialidades_medicas",
"id": 0,
"name": "Cardiologo",
"ind": "11",
"district": ""
},
{
"collection": "sub_cats",
"uid": "Av9vJ0EoFfxhAR2",
"class": "especialidades_medicas",
"id": 1,
"name": "Urologo",
"ind": "12",
"district": ""
}
]
var promises = [];
data.forEach(function (arrayItem) {
var docRef = firestore.collection(arrayItem.collection).doc(arrayItem.uid);
var objClass = {};
var objId = {};
objId[arrayItem.id] = { name: arrayItem.name, ind: arrayItem.ind };
objClass[arrayItem.class] = objId;
promises.push(docRef.set(objClass, { merge: true }));
});
</script>
</body>
</html>
we get this:
data structure current / needed
How would you modify this code to get the array / map structure?
Thanks a lot!!!
You will need to use arrayUnion() of fieldValue that can be used with set() or update(). So basically if you use it with update it will "merge" the new value with the existing array values in your document. Inside that you can have your map or any datatype you want.
An example code looks like this:
db.collection("users").doc(props.uid).update({
points: db.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});

Testing Node.js data processing

I'm trying to read some data from a locally stored JSON file, process it into separate JS objects, and append it to a queue. For the life of me, I can't find a way to test that my parsing function is working. To test that it works, I'm trying to pull the data from the local JSON file, and and print it to console. I think there's something conceptually that I don't understand, or a method to test this that I don't know of.
I cannot run the fs module in the browser even with Browserify. Firefox tells me that createReadStream is not a function.
index.html
<!DOCTYPE html>
<div id="container" style="position: relative; width: 100%; height: 700px;"></div>
<!-- <link rel="stylesheet" type="text/css" href="index.css" /> -->
<body>
<script type="text/javascript" src="parse.js"></script>
</body>
</html>
parse.js
//Assume JSON output = {attack source, attack destination, attack type}
//Required modules
//#ts-ignore: undeclared module
const watchStream = require('fs-watch-stream')
const es = require('event-stream')
const stream = require('JSONStream')
const fs = require('fs');
//Create websocket to receive json data instead?
//Save for later
//https.createServer(attacks).listen(9090)
function initial (){
var filepath = 'sample.json';
//Creates readable stream for JSON file parsing
var stream = fs.createReadStream(filepath, { encoding: 'utf8' }),
parser = stream.parse('*.');
//Send read data to parser function
return stream.pipe(parser);
}
initial()
.pipe(es.mapSync(function (data) {
console.log(data);
}));
sample.json
{
"employees": {
"employee": [
{
"id": "1",
"firstName": "Tom",
"lastName": "Cruise",
"photo": "https://jsonformatter.org/img/tom-cruise.jpg"
},
{
"id": "2",
"firstName": "Maria",
"lastName": "Sharapova",
"photo": "https://jsonformatter.org/img/Maria-Sharapova.jpg"
},
{
"id": "3",
"firstName": "Robert",
"lastName": "Downey Jr.",
"photo": "https://jsonformatter.org/img/Robert-Downey-Jr.jpg"
}
]
}
}
There's no need to involve the browser; just run node parse.js. Node.js has console.log too, and you will see the output in the console.
If you install fs-extra, you can use fs.readJson() to get the JSON as an object directly.

Display nested JSON data using 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.

Categories