How can I get access to the 'Roofing Insulation' array values in JS? Is it even possible with duplicate attribute names?
I have tried productListing['Roofing Insulation']['Roofing Insulation'] and many more types of syntax without success. I am aware the duplication is poor practice but it's all I have to work with...
{
"storeServices":{
"Local Services":[
"Rooftop",
"EPDM",
"Next-Day Delivery Available"
],
"National Services":[
"Covered",
"Window",
"Job Site Signs"
]
},
"productListing":{
"Roofing Insulation":{
"Roofing Insulation":[
"Celotex",
"Dow",
"Foamular",
"Johns Manville",
"Pactiv",
"Tyvek"
]
},
"Other Products":{
"Other Products":[
"Caulks/Sealants",
"Shutters",
"Tools & Equipment",
"Engineered Lumber",
"Roofing & Siding Accessories"
]
},
"Low Slope Roofing":{
"Low Slope Roofing":[
"Johns Manville",
"Mule-Hide Products",
"Versico"
]
},
"Steep Slope Roofing":{
"Concrete & Clay Roof Tiles":[
"Vande Hey Raleigh"
],
"Asphalt Shingles":[
"CertainTeed",
"GAF",
"Owens Corning"
]
},
"Windows & Doors":{
"Replacement Windows":[
"Pella"
],
"New Construction Windows":[
"Pella"
],
"Exterior Doors":[
"Pella"
],
"Skylights":[
"Velux"
]
},
"Siding":{
"Vinyl Siding":[
"Mastic Home Exteriors"
]
}
},
"branchDetails":{
"branchNumber":"1"
}
}
We can't help unless we see what you have tried and your code.
It should work if you do access it like below:
obj.productListing['Roofing Insulation']['Roofing Insulation']
Below is an example for you to showcase this:
var obj = {
"storeServices": {
"Local Services": [
"Rooftop",
"EPDM",
"Next-Day Delivery Available"
],
"National Services": [
"Covered",
"Window",
"Job Site Signs"
]
},
"productListing": {
"Roofing Insulation": {
"Roofing Insulation": [
"Celotex",
"Dow",
"Foamular",
"Johns Manville",
"Pactiv",
"Tyvek"
]
},
"Other Products": {
"Other Products": [
"Caulks/Sealants",
"Shutters",
"Tools & Equipment",
"Engineered Lumber",
"Roofing & Siding Accessories"
]
},
"Low Slope Roofing": {
"Low Slope Roofing": [
"Johns Manville",
"Mule-Hide Products",
"Versico"
]
},
"Steep Slope Roofing": {
"Concrete & Clay Roof Tiles": [
"Vande Hey Raleigh"
],
"Asphalt Shingles": [
"CertainTeed",
"GAF",
"Owens Corning"
]
},
"Windows & Doors": {
"Replacement Windows": [
"Pella"
],
"New Construction Windows": [
"Pella"
],
"Exterior Doors": [
"Pella"
],
"Skylights": [
"Velux"
]
},
"Siding": {
"Vinyl Siding": [
"Mastic Home Exteriors"
]
}
},
"branchDetails": {
"branchNumber": "1"
}
};
document.getElementById("demo").innerHTML = obj.productListing['Roofing Insulation']['Roofing Insulation'];
<p id="demo"></p>
Related
I'm new using JSON and I've created an API using Amazon's AWS service to work as a database for my dictionary website.
On the site there is a search bar which when receiving an input goes through my JavaScript to my JSON database to look for the search parameter given. For example "hello" as shown in the code below.
However my problem is that the only thing fetched to my JavaScript is the "hello" and none of the other things.
I know I'm new, but I would appreciate some tips on how i can make it possible using a search parameter get everything shown below.
[
{
"word": "hello",
"phonetic": "həˈləʊ",
"phonetics": [
{
"text": "həˈləʊ",
"audio": "//ssl.gstatic.com/dictionary/static/sounds/20200429/hello--_gb_1.mp3"
},
{
"text": "hɛˈləʊ"
}
],
"origin": "early 19th century: variant of earlier hollo ; related to holla.",
"meanings": [
{
"partOfSpeech": "exclamation",
"definitions": [
{
"definition": "used as a greeting or to begin a phone conversation.",
"example": "hello there, Katie!"
}
]
}
]
}
]
You can use filter to search through the array for a string matching the word.
let data = [
{
"word": "hello",
"phonetic": "həˈləʊ",
"phonetics": [
{
"text": "həˈləʊ",
"audio": "//ssl.gstatic.com/dictionary/static/sounds/20200429/hello--_gb_1.mp3"
},
{
"text": "hɛˈləʊ"
}
],
"origin": "early 19th century: variant of earlier hollo ; related to holla.",
"meanings": [
{
"partOfSpeech": "exclamation",
"definitions": [
{
"definition": "used as a greeting or to begin a phone conversation.",
"example": "hello there, Katie!"
}
]
}
]
},
{
"word": "TEST",
"phonetic": "həˈləʊ",
"phonetics": [
{
"text": "həˈləʊ",
"audio": "//ssl.gstatic.com/dictionary/static/sounds/20200429/hello--_gb_1.mp3"
},
{
"text": "hɛˈləʊ"
}
],
"origin": "early 19th century: variant of earlier hollo ; related to holla.",
"meanings": [
{
"partOfSpeech": "exclamation",
"definitions": [
{
"definition": "used as a greeting or to begin a phone conversation.",
"example": "hello there, Katie!"
}
]
}
]
}
]
let search = "HELLO";
let found = data.filter((row) => {
return (row.word.toLowerCase() == search.toLowerCase())
});
console.log(found)
I'm using ng2-tree https://angular2-tree.readme.io/v3.2.0/docs/inputs plugin
When i input below json it is showing as undefined
[
{
"value": "helper",
"name": "helper",
"children": []
},
{
"value": "taxi",
"name": "taxi",
"children": []
},
{
"value": "Cake",
"name": "Cake",
"children": [
{
"name": "Chocolate Fudge Cake",
"value": "Chocolate Fudge Cake"
},
{
"name": "Carrot & Walnut Cake",
"value": "Carrot & Walnut Cake"
}
]
}
]
with above json my result is as undefined you can see them in my provided link below
here is the stackblitz link: https://stackblitz.com/edit/angular-ng2-tree-aouyza?file=app/app.component.ts
Please help me thanks in advance!!
Your data structure is wrong. The tree component received as input param a TreeModel and you're having an array of TreeModels at the moment.
Either you adjust your data structure and use a parent TreeModel to wrap your current ones as its children, like following:
tree: TreeModel = {
value: 'Parent Model',
children: [
{
value: 'helper',
name: 'helper',
children: [],
},
{
value: 'taxi',
name: 'taxi',
children: [],
},
{
value: 'Cake',
name: 'Cake',
children: [
{
name: 'Chocolate Fudge Cake',
value: 'Chocolate Fudge Cake',
},
{
name: 'Carrot & Walnut Cake',
value: 'Carrot & Walnut Cake',
},
],
}
]
};
Or you iterate over the array in the HTML and use multiple tree components. That would look like following:
<tree [tree]="t" *ngFor="let t of tree"></tree>
For more information see the Github page of ng2-tree ;)
Update:
You still need to adjust the data model the way I suggested but you can hide the empty root node. To do so, you need to do following:
HTML
<tree [tree]="tree" [settings]="{ rootIsVisible: false }"></tree>
Due to this setting a class rootless is applied which hides the empyt root node but only if you've added node_modules/ng2-tree/styles.css to your angular.json or you've added a custom implementation for that class.
You can find the settings doc here.
I am new to mongodb and im trying to (as title says) "Given an array of matches, find all documents that have atleast one match and replace all matches with given value"
For example, lets say i have those documents in my mongodb:
[
{
"_id": ObjectId("5e90880a39cfeaaf0b97b576"),
"StudentName": [
"Chris, C",
"David, O",
"Mike, K",
"Sam, Bard"
]
},
{
"_id": ObjectId("5e90880a39cfeaaf0b97b577"),
"StudentName": [
"Joe, J",
"John, K",
"David, O",
"Sam, Ba rd",
"Sam, B"
]
}
]
And i want to find all documents that contains either ["Sam, B", "Sam, Bard", "Sam, Ba rd"] and replace with "Sam"
Expected result:
[
{
"_id": ObjectId("5e90880a39cfeaaf0b97b576"),
"StudentName": [
"Chris, C",
"David, O",
"Mike, K",
"Sam"
]
},
{
"_id": ObjectId("5e90880a39cfeaaf0b97b577"),
"StudentName": [
"Joe, J",
"John, K",
"David, O",
"Sam",
"Sam"
]
}
]
What i tried to do:
db.collection.updateMany({ "StudentName": {"$in":["Sam, B", "Sam, Bard", "Sam, Ba rd"]} },{ "$set": { "StudentName.$": "Sam" } })
Which didn't work. Any help? Thank you very much.
EDIT1: I need it to be dynamic, i'll be providing the array of possibles matches and the string to replace with through a NodeJS application.
EDIT2: To give an example for EDIT1, i could pass an array like this ["John,"Bob","Jessica","Robert"] to replace with "Josh"
There are several ways you can do this. By the looks of it you want this to be done via one command that can be run directly in the shell.
You can do this leveraging arrayFilters option within updateMany. See https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/#std-label-updateMany-arrayFilters for further documentation on it.
For simplicity I won't leverage indices so the below command would iterate over all the documents in the collection. If you want to leverage an index you would just adjust the query portion of the updateMany
db.collection.updateMany(
{ },
{ $set: { "StudentName.$[element]" : "Sam" } },
{ arrayFilters: [ { "element": /.*Sam.*/i } ] }
)
The above will replace any value that contains "Sam" with the value "Sam". So "Sam I Am" would be replaced with "Sam".
If you know the values you are trying to replace:
db.students.updateMany(
{ },
{ $set: { "StudentName.$[element]" : "Ana" } },
{ arrayFilters: [ { "element": { $in: ["John", "Jessica", "Robert", "Rob"] } } ] }
)
which would replace all values of John, Jessica, Robert and Rob with "Ana".
I would to edit a code source from English to french. In the database a table has a colum with data enum('Male','Female') that I wish to change into enum('Homme','Femme'). Impossible and I receive a message like data truncated for colum 3.
I find the same information in some java file. When I change it only without change the database I receive the same errors.
What can I do?
this a part of code in lib.js
EmployeeAdapter.method('getFormFields', function() {
var newFields = [];
var tempField, title;
var fields = [
[ "id", {"label":"ID","type":"hidden","validation":""}],
[ "employee_id", {"label":"Employee Number","type":"text","validation":""}],
[ "first_name", {"label":"First Name","type":"text","validation":""}],
[ "middle_name", {"label":"Middle Name","type":"text","validation":"none"}],
[ "last_name", {"label":"Last Name","type":"text","validation":""}],
[ "nationality", {"label":"Nationality","type":"select2","remote-source":["Nationality","id","name"]}],
[ "birthday", {"label":"Date of Birth","type":"date","validation":""}],
[ "gender", {"label":"Gender","type":"select","source":[["Male","Male"],["Female","Female"]]}],
[ "marital_status", {"label":"Marital Status","type":"select","source":[["Married","Married"],["Single","Single"],["Divorced","Divorced"],["Widowed","Widowed"],["Other","Other"]]}],
[ "ethnicity", {"label":"Ethnicity","type":"select2","allow-null":true,"remote-source":["Ethnicity","id","name"]}],
[ "immigration_status", {"label":"Immigration Status","type":"select2","allow-null":true,"remote-source":["ImmigrationStatus","id","name"]}],
[ "ssn_num", {"label":"SSN/NRIC","type":"text","validation":"none"}],
[ "nic_num", {"label":"NIC","type":"text","validation":"none"}],
[ "other_id", {"label":"Other ID","type":"text","validation":"none"}],
[ "driving_license", {"label":"Driving License No","type":"text","validation":"none"}],
[ "employment_status", {"label":"Employment Status","type":"select2","remote-source":["EmploymentStatus","id","name"]}],
[ "job_title", {"label":"Job Title","type":"select2","remote-source":["JobTitle","id","name"]}],
[ "pay_grade", {"label":"Pay Grade","type":"select2","allow-null":true,"remote-source":["PayGrade","id","name"]}],
[ "work_station_id", {"label":"Work Station Id","type":"text","validation":"none"}],
[ "address1", {"label":"Address Line 1","type":"text","validation":"none"}],
[ "address2", {"label":"Address Line 2","type":"text","validation":"none"}],
[ "city", {"label":"City","type":"text","validation":"none"}],
[ "country", {"label":"Country","type":"select2","remote-source":["Country","code","name"]}],
[ "province", {"label":"State","type":"select2","allow-null":true,"remote-source":["Province","id","name"]}],
[ "postal_code", {"label":"Postal/Zip Code","type":"text","validation":"none"}],
[ "home_phone", {"label":"Home Phone","type":"text","validation":"none"}],
[ "mobile_phone", {"label":"Mobile Phone","type":"text","validation":"none"}],
[ "work_phone", {"label":"Work Phone","type":"text","validation":"none"}],
[ "work_email", {"label":"Work Email","type":"text","validation":"emailOrEmpty"}],
[ "private_email", {"label":"Private Email","type":"text","validation":"emailOrEmpty"}],
[ "joined_date", {"label":"Joined Date","type":"date","validation":""}],
[ "confirmation_date", {"label":"Confirmation Date","type":"date","validation":"none"}],
[ "termination_date", {"label":"Termination Date","type":"date","validation":"none"}],
[ "department", {"label":"Department","type":"select2","remote-source":["CompanyStructure","id","title"]}],
[ "supervisor", {"label":"Direct Supervisor","type":"select2","allow-null":true,"remote-source":["Employee","id","first_name+last_name"]}],
[ "indirect_supervisors", {"label":"Indirect Supervisors","type":"select2multi","allow-null":true,"remote-source":["Employee","id","first_name+last_name"]}],
[ "approver1", {"label":"First Level Approver","type":"select2","allow-null":true,"null-label":"None","remote-source":["Employee","id","first_name+last_name"]}],
[ "approver2", {"label":"Second Level Approver","type":"select2","allow-null":true,"null-label":"None","remote-source":["Employee","id","first_name+last_name"]}],
[ "approver3", {"label":"Third Level Approver","type":"select2","allow-null":true,"null-label":"None","remote-source":["Employee","id","first_name+last_name"]}],
[ "notes", {"label":"Notes","type":"datagroup",
"form":[
[ "note", {"label":"Note","type":"textarea","validation":""}]
],
And the structure of the table is
ALTER TABLE `employees` CHANGE `gender` `gender` ENUM('Male','Female')
CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;
If I wish to change Male, female, Married etc into french.
When I do it I receive truncated error.
Sorry for my english caus I'm french
I am struggling to retrieve some values from a JSON file formatted like this:
{
"#context": [
"https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld",
{
"wx": "https://api.weather.gov/ontology#",
"#vocab": "https://api.weather.gov/ontology#"
}
],
"type": "FeatureCollection",
"features": [
{
"id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-95.45,
32.36
],
[
-96.07,
32.36
],
[
-96.08,
32.76
],
[
-95.92,
32.82
],
[
-95.85,
32.77
],
[
-95.77,
32.77
],
[
-95.76,
32.75
],
[
-95.71,
32.75
],
[
-95.66,
32.71
],
[
-95.64,
32.72
],
[
-95.59,
32.68
],
[
-95.6,
32.48
],
[
-95.47,
32.37
],
[
-95.45,
32.36
]
]
]
},
"properties": {
"#id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
"#type": "wx:Alert",
"id": "NWS-IDP-PROD-2485131-2320093",
"areaDesc": "Van Zandt",
"geocode": {
"UGC": [
"TXC467"
],
"SAME": [
"048467"
]
},
"references": [],
"sent": "2017-08-13T00:03:41+00:00",
"effective": "2017-08-13T00:03:41+00:00",
"onset": "2017-08-13T00:03:00+00:00",
"expires": "2017-08-13T01:00:00+00:00",
"ends": "2017-08-13T01:00:00+00:00",
"status": "Actual",
"messageType": "Alert",
"category": "Met",
"severity": "Severe",
"certainty": "Observed",
"urgency": "Immediate",
"event": "Severe Thunderstorm Warning",
"sender": "NWS Fort Worth TX",
"headline": "Severe Thunderstorm Warning issued August 12 at 7:03PM CDT expiring August 12 at 8:00PM CDT by NWS Fort Worth TX",
"description": "The National Weather Service in Fort Worth has issued a\n\n* Severe Thunderstorm Warning for...\nVan Zandt County in north central Texas...\n\n* Until 800 PM CDT.\n\n* At 703 PM CDT, a severe thunderstorm was located near Wills Point,\nmoving east at 25 mph.\n\nHAZARD...65 mph wind gusts and quarter size hail.\n\nSOURCE...Radar indicated.\n\nIMPACT...Hail damage to vehicles is expected. Expect wind damage\nto roofs, siding, and trees.\n\n* This severe thunderstorm will be near,\nCanton around 710 PM CDT.\nEdgewood around 715 PM CDT.\nFruitvale around 725 PM CDT.\nGrand Saline around 735 PM CDT.\nVan around 750 PM CDT.\n\nThis includes Interstate 20 between mile markers 513 and 542.",
"instruction": "For your protection get inside a sturdy structure and stay away from\nwindows.\n\nContinuous cloud to ground lightning is occurring with this storm.\nMove indoors immediately. Lightning can kill.\n\nHeavy rainfall is occurring with this storm, and may lead to flash\nflooding. Do not drive your vehicle through flooded roadways.",
"response": "Shelter",
"parameters": {
"eventMotionDescription": [
"2017-08-13T00:03:00.000-05:00...storm...277DEG...23KT...32.62,-95.97"
],
"hailSize": [
"1.00"
],
"windGust": [
65
],
"tornadoDetection": [
"POSSIBLE"
],
"VTEC": [
"/O.NEW.KFWD.SV.W.0313.170813T0003Z-170813T0100Z/"
],
"EAS-ORG": [
"WXR"
],
"PIL": [
"FWDSVRFWD"
],
"BLOCKCHANNEL": [
"CMAS",
"EAS",
"NWEM"
],
"eventEndingTime": [
"2017-08-13T01:00:00Z"
]
}
}
},
I am trying to get the values from the keys under the "properties" key. What I am struggling with is does the array start with "properties" nested under #context or under "features"? I am not familiar with JSON data that uses # keys.
There are more values I need. But for starters, I am just using the event key nested under "features" -> "properties" where most of the keys for the values I need. I am not getting output from that.
<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($data, true); // decode the JSON feed
foreach($results as $result) {
dump($result); //this will dump the array
foreach($results['features'] as $data) {
dump($data['event']);
}
}
?>
-Thanks
EDIT: Added suggestion to code for json_decode
As others have stated, you need to pass true as a second param to json_decode if you want to the result to be an associative array.
The hierarchy is features/properties/event so you can look through the features and pull what you want out of the properties of each feature.
<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$results = json_decode($data, true); // decode the JSON feed
foreach($results['features'] as $currFeature)
{
$currEvent = $currFeature['properties']['event'];
echo $currEvent."\n";
}
Use json_decode($data, true). The true tells json_decode to return nested associative arrays instead of a object.
As BarNakedCoder said:
json_decode($data, true)
but you also need to replace
dump($data['event']
with:
dump($data[0]['event'])