parsing json multiple array with unknown field names with jquery - javascript

I have json data that looks like this
{
"projects":{
"COMMERCIAL":[
{
"ppID":"87",
"pTitle":"5th Street Lofts"
},
{
"ppID":"94",
"pTitle":"Skip-a-Long Child Development Services"
}
],
"CORPORATE":[
{
"ppID":"86",
"pTitle":"Caxton Building"
},
{
"ppID":"68",
"pTitle":"Swiss Valley Corporate Headquarters"
}
],
"EDUCATION (COLLEGIATE)":[
{
"ppID":"20",
"pTitle":"Ashford University - Athletic Field"
},
{
"ppID":"64",
"pTitle":"St. Ambrose University - Center For Health And Science Education"
}
]
},
"error":"0"
}
In this example, "COMMERCIAL", "CORPORATE", and "EDUCATION (COLLEGIATE)" are unknown fields names.
I'm getting it from my CGI, which looks like this:
$.ajax({
url: "cgi/myCGI.exe",
dataType: "json",
error: ajaxError,
success: function(json){
if(json.error !== "0"){
alert("error processing request: "+json.error);
return;
}
var temp="";
var i=0;
for(i=0;i<=json.projects.length-1;i++){
// tried something like this
}
$.each(json.projects, function(ppID, pTitle) {
// tried something like this
});
// add to my html
}
});
Ultimately, I want to add HTML to the webpage,
like
<div class="smSubTitle">COMMERCIAL</div>
Fidlar Technologies<br>
Skip-a-Long Child Development Services<br>
<div class="smSubTitle">CORPORATE</div>
etc.
I can't figure out how to get the names of each project "sub title" then it's individual field values.
EDIT:
First, I noticed that json.projects.length is undefined.
I also tried json.projects[0].length but it is also undefined.
in
$.each(json.projects, function(ppID, pTitle) {
console.log("test: "+ppID);
console.log("test: "+pTitle);
});
ppID works, but pTitle says [object,object]

projects property is an object and each object property contains an array. So you have to at first iterate through the object's keys and then the arrays, i.e. 2 nested loops:
var html = '', projects, type, i;
for ( type in json.projects ) {
if ( json.projects.hasOwnProperty(type) ) {
// append the type of the projects
html += "<div class='smSubTitle'>" + type + "</div>";
projects = json.projects[type];
// iterate through each array
for ( i = 0; i < projects.length; i++ ) {
html += "<a href='somePage.html?id="+ projects[i].ppID+ "'>"+ projects[i].pTitle +"</a><br>";
}
}
}
Here is a demo.

I think you have a misunderstanding of what JSON is. JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old Javascript Object. They are different.
That said, you can iterate over these objects like so:
Object.keys(json.projects).forEach(function(key, i) {
// key is "COMMERCIAL", "CORPORATE", ...
// You can add the smSubTitle element here
json.projects[key].forEach(function(item) {
// item is an object {ppID: '...', pTitle: '...'}
// You can add a link per object here
});
});

Related

Javascript - Add Array of Objects to existing Array of Objects

I have a Customer with Apples, I have an Api Controller that takes an Object Customer as a parameter, and updates the existing one in the database with these new Apples:
[HttpPut("Update")]
public async void Put([FromBody]Customer customer)
{
await _repository.UpdateCustomer(customer);
}
Using Javascript, I want to add these new Apples to my current List of Apples in the Customer. From reading on SO it should look something like:
addApplesToCustomer_method: function () {
var updatedCustomer = this.currentCustomer;
Array.prototype.push.apply(updatedCustomer.apples, this.selectedApples);
$.ajax({
url: 'api/customer/update',
type: 'PUT',
contentType: "application/json",
data: JSON.stringify({
customer: updatedCustomer
}),
success: function () {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + '\n' + errorThrown);
}
});
}
currentCustomer is the customer we want to update. selectedApples is the new List of Apples we want to add to our Customers existing Array of Apples.
The above however does not even run since I added the Array.prototype.push.apply(updatedCustomer.apples, this.selectedApples) but it doesnt give me an error either. Just nothing happens. If I go back to sending the Customer and Apples seperately to my Controller it works, but I don't want to do that.
Use spread syntax.
updatedCustomer.apples.push(...this.selectedApples);
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected, or an object
expression to be expanded in places where zero or more key-value pairs
(for object literals) are expected.
How about just pushing the object onto the array withArray.push(object)
let objectArray = []
let apple = {
name: 'Apple',
size: 'medium'
}
let orange = {
name: 'Orange',
size: 'large'
}
// Create an initial list with apples
for (var i = 0; i < 10; i++) {
objectArray.push(apple)
}
// Now add an orange to that list
objectArray.push(orange)
// The resulting array contains 10 apples, 1 orange.
console.log(objectArray)
Here's the JSFiddle: http://jsfiddle.net/j7kcjjqh/
(Inspect the console to see the result)

How do I map a variable to object

I'm new to JSON and jQuery/JavaScript.
How would I pull in a object so that I can use it within jQuery, I've tried 2 attempts
var placements = document.querySelector(placements)
var message = document.querySelector(placements.message)
$.ajax({
type: 'GET',
url: 'https://raw.githubusercontent.com/kieranbs96/developer-exercise/master/data/recommendations.json',
async: false,
dataType: 'json',
success: function (data) {
$("header").append(placements.message);
}
});
Below is the JSON I'm trying to pull in:
{
"placements":[
{
"message":"If you like this, you might be into these",
"items":[
{
"id":"029148",
"name":"Woodblock Play Suit",
"price":"46.00"
},
{
"id":"0294526806",
"name":"Smock Dress",
"price":"39.00"
},
{
"id":"0297180006",
"name":"Cami",
"price":"9.00"
},
{
"id":"0298473606",
"name":"Asymmetric Wrap Cami Dress",
"price":"46.00"
},
{
"id":"0297155306",
"name":"Casual Stripe Tee",
"price":"16.00"
}
]
}
]
}
Marked as duplicate - the other question did not solve my problem - it has been solved by an answer to this question.
You haven't included what the error is or the expected output, but here's two potential errors.
You aren't utilizing the data object returned from your AJAX request.
The value associated with the placements key on your JSON object is an array of objects. Therefore, to access the message key, you'll need to traverse the array.
This is likely what your code should look like:
$("header").append(data.placements[0].message);
First off, you're missing the data object within your append function.
Second, you're missing the key notation of data.placements considering the fact that placements is an array.
You can either use data.placements[0].message to get your preferred data, or, if placements will be extended with more objects in the future, map through your objects like this:
data.placements.map(function(obj, index){
if(index == 0){
$("header").append(obj.message);
}
})
Not necessary if your array will always have a length of 1 of course

How to extract data from JSON object

I am using Google Script to fetch an url that returns me the following JSON object:
[
{
"rsid":"op-bigideas",
"site_title":"Big Ideas",
"evars":[
{
"name":"Tracking Code",
"type":"text_string",
"id":"trackingcode",
"expiration_type":"week",
"expiration_custom_days":"1",
"allocation_type":"most_recent_last"
},
{
"name":"Custom eVar 1",
"description":"",
"type":"text_string",
"enabled":false,
"id":"evar1",
"expiration_type":"visit",
"expiration_custom_days":1,
"allocation_type":"most_recent_last"
}
]
}
]
How can I extract the name property from evars using javascript with Google Apps Script?
This is the code that returns me the JSON object:
var elements = JSON.parse(UrlFetchApp.fetch(url, options));
I already tried the following but only receiving undefined message:
1.
for(var elem in elements) {
Logger.log(elements[elem]['evars'].name);
}
2.
for(var elem in elements) {
Logger.log(elements[elem].evars.name);
}
3.
var newData = JSON.parse(elements);
Logger.log(newData.evars.name)
If I understand you correctly, you want to get the values of the name properties. This code will log the name properties:
for (var elem in elements) {
for (var evar in elements[elem].evars) {
Logger.log(elements[elem].evars[evar].name);
}
}
This will output:
"Tracking Code"
"Custom eVar 1"
There are multiple name properties for each element, so I think you want to map twice:
elements.map(function(elt) {
return !elt.evars ? [] : elt.evars.map(function(evar) {
return evar.name;
});
});
This will give you an array of arrays; the outer array is the elements, each of which contains an array of the names. For your example, this will be:
[
["Tracking Code", "Custom eVar 1"]
]
for (var elem in elements[0].evars) {
Logger.log(elements[0].evars[elem].name);
}

jQuery getJSON print array where name is string

I have some good practice with using php and mysql, and am now starting with JSON.
I've made a simple json index containing paths to folders, and items inside them:
{ "foldery" : [
{
"foName": "website/img/bg",
"files" : [
"website/img/bg/bg1.jpeg",
"website/img/bg/bg2.jpg",
"website/img/bg/bg3.jpg",
"website/img/bg/bg4.jpeg"
]
},
{
"foName": "website/img/post1",
"files" : [
"website/img/post1/a.jpeg",
"website/img/post1/b.jpg",
"website/img/post1/c.jpeg",
"website/img/post1/d.jpg"
]
}
]
}
Now here is my jquery, for now returning a big mess of data, somewhere including the info about the contents inside:
$.getJSON("nameindex.json", function(data) {
console.log(data);
});
What I would like it to do, in mySql looks like this:
SELECT files FROM foldery WHERE foName = "website/img/post1"
Thus the result, would be an array containing all the files inside post1.
Unfortunately tho, after 2 hours of attempts I have nothing more than the simple console.log code.
Any help would be gladly appreciated
You need to iterate over your array and check forName to equality
function select(o, foName) {
var length = o.foldery.length;
for(var i = 0; i < length; i++){
if (o.foldery[i].foName == foName) {
return o.foldery[i].files;
}
}
}
var result = select(o, "website/img/post1")
console.log(result);
Result
[ 'website/img/post1/a.jpeg',
'website/img/post1/b.jpg',
'website/img/post1/c.jpeg',
'website/img/post1/d.jpg' ]

How do I find a JSON object using a nested expression?

From the example JSON below, I would like to return the target.id value of an object where the source.id == 'x'.
So where source.id == 'startId' return target.id == '3eecd840-e6a8-423c-a892-7df9646fde5d'.
{
"line":[
{
"type":"link",
"source":{
"id":"startId",
"port":"out"
},
"target":{
"id":"3eecd840-e6a8-423c-a892-7df9646fde5d",
"port":"in"
},
"id":"87d88a26-3a28-4db0-8016-71c1c4665f14"
},
{
"type":"link",
"source":{
"id":"3eecd840-e6a8-423c-a892-7df9646fde5d",
"port":"outYes"
},
"target":{
"id":"49940c02-70f2-4c53-ab50-9cbf96903600",
"port":"in"
},
"id":"9f8c365e-9ca7-440f-a722-c4f340782c0c"
}
]
}
I've tried JSONPath, but I cannot work out the expression to use. $.line[*].source.id gives me a list of source id's and $.line[?(#.source.id=='startId')] returns an error.
I also understand that I could iterate through each object in code, but It wouldn't be very efficient if I have tens or hundreds of 'lines' to work through. If possible I would like a more 'direct' path to the object.
I'm using javascript to code the rest of the app, so javascript examples would be helpful (with or without JSONPath).
If you're getting json as string, then use var json = JSON.parse(jsonStr). Then you can do it with Array.filter
var result = json.line.filter(function(obj){
return obj.source.id == "startId"
});
Then you could get the values like this
var ids = result.map(function(o){ return o.target.id });

Categories