parsing JSON embedded structure - json

My JSON response comes like below:
"channels": {
"BB0AC397-78AA-41C9-818A-A52A6BC81E9B": {
"id": "BB0AC397-78AA-41C9-818A-A52A6BC81E9B",
"name": "MyVABotChannel",
},
"94612845-7868-4B1C-8E58-7BD88869B197": {
"id": "94612845-7868-4B1C-8E58-7BD88869B197",
"name": "System_Bot_Test",
}
my requirement is to extract the id of the structure where name is MyVABotChannel. the id are not fixed and random when they will come from server. so how do i find the id corresponding to the specific name.

Assuming javascript
This snippet assumes multiple entries with "MyVABotChannel"
// response = JSON
var values = Object.values(response.channels);
var botChannels = values.filter(channel => channel.name === "MyVABotChannel");
This snippet assumes one entry with "MyVABotChannel"
// response = JSON
var values = Object.values(response.channels);
var botChannels = values.find(channel => channel.name === "MyVABotChannel");

If it's in JavaScript or any library that exposes a JSON DOM, then like so:
var channels = ...
var key = Object
.getKeys( channels )
.find( e => chanels[e].name == "MyVABotChannel" );
if( key == null ) {
console.log("Couldn't find element.");
return;
}
var result = channels[key].id;
console.log( result );

Related

How to get value only from json array using Jquery?

I am trying to get the value only from a json array. I have search some answer in stackoverflow but seems like not the one for me.
my code looks like this:
.done(function (data) {
var jdata = JSON.stringify(data['queryBuilder']);
var arrdata = JSON.parse(jdata);
var fdata = JSON.stringify(arrdata);
printtopdf(fdata);
);
//this code is from the answer posted here in stackoverflow:
function printtopdf(fdata) {
var values = Object.keys(fdata).map(function (key) { return fdata[key]; });
console.log(fdata);
}
and the result:
[
{
"rownum":2,
"rr_id":"RR2100001",
"ref_id":"UCL2100001",
"cdescription":"65UGHDFH56Y</br>, 65UGHDFH56Y</br>",
"rr_status":"Pending",
"date_created":"2021-01-08 13:46:03"
}
]
I just want to get the value only, like this:
[
2,
"RR2100001",
"UCL2100001",
"65UGHDFH56Y</br>, 65UGHDFH56Y</br>",
"Pending",
"2021-01-08 13:46:03"
]
Any idea? thanks.
You can achieve this using Array.prototype.map and Object.prototype.values.
const data = [
{
"rownum":2,
"rr_id":"RR2100001",
"ref_id":"UCL2100001",
"cdescription":"65UGHDFH56Y</br>, 65UGHDFH56Y</br>",
"rr_status":"Pending",
"date_created":"2021-01-08 13:46:03"
}
];
// Get values for all data points
const v1 = data.map(value => Object.values(value));
console.log(v1);
// Get values for first data point
const v2 = Object.values(data.shift());
console.log(v2);

Nested Json from nested mysql queries in Nodejs/ExpressJs

I m fetching data from mysql database in nodejs/expressjs and want to create nested json from it.
I want to create Json object like this :
[
{id : 1,countryName:'USA',population:10000,
cities : [
{id:1,cityName:'NY',countryId:1},{id:2,cityName:'Chicago',countryId:1}
]
},
{id : 2,countryName:'Canada',population:20000,
cities : [
{id:1,cityName:'Toronto',countryId:2},{id:2,cityName:'Ottawa',countryId:2}
]
}
]
here is my code in expressJs but it is giving me an empty array of JSON
app.get("/checkJson",function(req,res){
var country = {};
var outerobj = {};
var outerArray = [];
conn.query("select * from country",function(err,result){
for(var i = 0 ;i<result.length;i++){
var cityobj = {};
var city = [];
conn.query("select * from city where countryId ="+result[i].id,function(err,cityResult){
for(var j = 0;j<cityResult.length;j++){
cityobj = {cityName:cityResult[j].name,countryId:cityResult[j].countryId};
city.push(cityobj);
} //end city forloop
}) //end city Query
outerobj = {id:result[i].id,countryName:result[i].name,pop:result[i].population,cities:city};
outerArray.push(outerobj);
} //end country forloop
}) // end country query
console.log(outerArray);
})
MySQL returns flat objects. We want to nest joined objects.
Let's say we have courses table, each course belongs to a department and has various course sections. We would like to have a resulting courses array that has a department object property within it and have a list of course sections.
This is a good solution from kyleladd on github
https://github.com/ravendano014/node-mysql-nesting

Parse random String & return Value (JSON)

Edit: It works pretty well now and this makes it possible to reference URLs in a JSON file and return their related pairs (e.g game name / year / image url). Here's the code.
AFRAME.registerComponent('jfetch', {
schema: {},
init: function () {
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsongames = JSON.parse( event.target.response )
var keys = Object.keys(jsongames);
var random = jsongames[keys.length * Math.random() << 0];
var games = random.Title + ' (' + random.Developer + ')'
var textEntity = document.querySelector('#text');
textEntity.setAttribute("value", games)
var gurl = random.Imageurl
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:gurl});
} );
request.send( null );
}
});
Thanks for the help everyone!
Original Question: I would like to fetch a random "Title" string in my Json file and return its corresponding value. I know the simple test code works but I have no idea how to apply it to an array with lots of objects and to add the random parsing element. Can someone please help me with a solution? This is my remix file.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonGames = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonGames.Title)
} );
request.send( null );
}
});
You can not manipulate JSON file as you would with an object, because JSON is a string. Thats why we parse them (converting into Javascript object).
From your question I assume that you want to get a random value of key-value pairs, where key is a Title. In that case, first you parse JSON response (as you do already - var jsonGames = JSON.parse( event.target.response )). So now you have your Javascript object to work with - jsonGames and all what is left is to get that random key of it. To do that you can, for ex:
var jsonGames = JSON.parse( event.target.response )
var keys = Object.keys(jsonGames);
var random = jsonGames[keys[keys.length * Math.random() << 0]];
textEntity.setAttribute("value", random.Title)
Please comment if something is not right.

How to access json nested objects in node.js

I have used xml2js parser to parse the xml file in node.js. It is parsing the xml successfully. But now i want to parse the json or to identify the particular data in json.
My node.js code
var fs = require('fs');
var parseString = require('xml2js').parseString;
var xml = 'C:\\temp\\Masters.xml';
var fileData = fs.readFileSync(xml,'utf8');
parseString(fileData, function (err, result) {
console.log(JSON.stringify(result));
var json = JSON.stringify(result);
var jsonObj = JSON.parse(json);
for (var key in jsonObj) {
console.dir(key + ": " + jsonObj[key].Customer_Name);
}
});
In console output:
'Masters: undefined'
Json data:
'{"Masters":
{
"Customer":
[
{"Customer_Name":["Kim"],
"Customer_Code":["c86"],
"Date":["23-11-15"],
"Address":["Narhe"],
"City":["Pune"],
"State":["Maharashtra"],
"TIN":["3365670"],
"PAN_Number":["AAAAA1111a"],
"Mobile_Number":["8999000090"],
"Email_ID":["amitshirke#gmail.com"],
"Contact_Person":["Anish"],
"Opening_Balance":["0"] },
{"Customer_Name":["Ankit"],
"Customer_Code":["c87"],
"Date":["12-04-15"],
"Address":["Narhe"],
"City":["Pune"],
"State":["Maharashtra"],
"TIN":["336567"],
"PAN_Number":["AAAAA1111p"],
"Mobile_Number":["8900000000"],
"Email_ID":["amitshirke1#gmail.com"],
"Contact_Person":["Anuj"],
"Opening_Balance":["0"] }
]
}
}'
In above data, Masters is root element(Object), Customer is another nested object and there two customers. Then how can I access the customer names or how to use the for loop to access the same?.
Thanks in advance.
You can access the Customer array as follows -
var customerArray = Masters.Customer,
length = customerArray.length;
for(var i = 0; i < length; i++)
{
// You can access the customers array from here -
console.log(customerArray[i].Customer_Name[0]); // [0] hardcoded because as you can see all the variables are in array at 0th position
// similarly you can access other data
console.log(customerArray[i].City[0]);
}

Parsing Google Maps JSON data for Geocoding in JQ (Not JQuery)

I am trying to get the Country and City names from Lat and Long values with JQ.
Here is the full example JSON
https://maps.googleapis.com/maps/api/geocode/json?latlng=55.397563,10.39870099999996&sensor=false
I pasted returned JSON in jqplay,
Tried to select Country and City names, but the closest I get is
.results[0].address_components[].short_name
How can I specify just bring the nodes where "types" : [ "country", "political" ] ?
Thanks
It's unclear to me what exactly you're looking for. Each result has a set of types, each address component also has a set of types. Which one did you want? We can write a filter that will match what you attempted but considering the data, it will be completely useless to you. The only item that contains the types you listed is just a country name.
Anyway, assuming you wanted to get a result object that had the types "country" and "political", use the contains() filter.
.results | map(
select(
.types | contains(["country","political"])
)
)
Otherwise you'll need to clarify what exactly you wanted from this data set. An example of the expected results...
I wrote a function to do this.
/**
* geocodeResponse is an object full of address data.
* This function will "fish" for the right value
*
* example: type = 'postal_code' =>
* geocodeResponse.address_components[5].types[1] = 'postal_code'
* geocodeResponse.address_components[5].long_name = '1000'
*
* type = 'route' =>
* geocodeResponse.address_components[1].types[1] = 'route'
* geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse, shortName) {
for(var i=0; i < geocodeResponse.address_components.length; i++) {
for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
if (geocodeResponse.address_components[i].types[j] == type) {
if (shortName) {
return geocodeResponse.address_components[i].short_name;
}
else {
return geocodeResponse.address_components[i].long_name;
}
}
}
}
return '';
}
The way to use it; an example:
...
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results[1]) {
var country = addresComponent('country', results[1], true);
var postal_code = addresComponent('postal_code', results[1], true);
...
}
});
...
I used it here: saving marker data into db
Assign the json to results variable, var results = {your json}.
Then try this :
for( var idx in results.results)
{
var address = results.results[idx].address_components;
for(var elmIdx in address)
{
if(address[elmIdx].types.indexOf("country") > -1 &&
address[elmIdx].types.indexOf("political") > -1)
{
address[elmIdx].short_name //this is the country name
address[elmIdx].long_name //this is the country name
}
}
}