JSON data parse - javascript

$scope.partsLinesTest = data[0].instock; // this is getting the JSOn data
from my http request
for(var i=0; $scope.partsLinesTest.length > 0; i++) {
//$scope.partsLinesTest = $scope.partsLinesTest[0].instock;
console.log($scope.partsLinesTest.replace(/['{[\]}']/g,''))
var str = $scope.partsLinesTest;
$scope.partsLinesStock = str.replace(/['{[\]}']/g,'');
}
The Json data is somewhat formatted as below, my problem is with instock due to the extra regular brackets and curly braces which is why I thought using RegEX would solve problem, however I can't seem to iterate correctly through the data and post it back into the view, also I'm using Angular
var test = [
{
"id": 1,
"title": "This is a document",
"desc": "PO",
"date": "2017-01-15",
"instock": "[{'branch': 'Edmonton', 'quantity': 2}]"
}

A working temporary solution (no, better, a temporary workaround) would be to use Javascript's eval() function (which you should never do on a production system because it opens up security holes!):
var test = [
{
"id": 1,
"title": "This is a document",
"desc": "PO",
"date": "2017-01-15",
"instock": "[{'branch': 'Edmonton', 'quantity': 2}]"
}]
console.log(eval(test[0].instock))
console.log(Array.isArray(eval(test[0].instock)))
As #Quentin pointed out, the correct solution would be to make the server emit correctly formatted JSON (which would require replacing the single quotes ' by escaped double quotes \").
Please read about why using eval() is strongly discouraged: Why is using the JavaScript eval function a bad idea?

If it's JSON-esque you know it will have , and : dividing keys and values. I would start by cleaning out all other characters and splitting it on those:
var jsonString = "[{'branch': 'Edmonton', 'quantity': 2}]"
var cleaned = jsonString.replace(/[^a-zA-Z0-9:,]/g,'')
//"branch:Edmonton,quantity:2"
var splitIntoKeyVal = cleaned.split(',').map(function(row){ return row.split(':')})
//[["branch","Edmonton"],["quantity],2]]
var json = {}
splitIntoKeyVal.forEach(function(row){
json[row[0]] = row[1]
})
If you think your values might have : or , in them, you might have to do some other regex trickery.

In order to get the quantity you must parse the data.instock json.
var data = {
"id": 1,
"title": "This is a document",
"desc": "PO",
"date": "2017-01-15",
"instock": '[{"branch": "Edmonton", "quantity": 2}]'
};
var stock = JSON.parse(data.instock);
console.log(stock[0].quantity);
//$scope.partsLinesStock = stock[0].quantity;

Related

Setting HTML text using a loop

I'm currently running a REST query against a SharePoint list and I'm trying to display the results with a $().text() script. I have it working but would think there's a more efficient way. I have many fields I need to set but they're sequentially numerical and just think there should be a better way. Example below:
$('#div1Id').text(data.d.results[0].slot1);
$('#div2Id').text(data.d.results[0].slot2);
$('#div3Id').text(data.d.results[0].slot3);
Etc x20 fields...
I tried below, but I'm sure for reasons that are obvious to you all that know what you're doing this didn't work. The "divId" loads fine but the dataId shows the text "data.d.results[0].slot1"/2/3/etc instead of the actual data.d.results:
for (i=1;i<21;i++){
var divId = "#div"+i+"Id";
var dataId = "data.d.results[0].slot"+i;
$('+divId+').text(dataId);
}
Based on what your first example was doing, I think you want this:
for (i = 1; i < 21; i++) {
var divId = "#div" + i + "Id";
// access the value from the "slot#" property of the object
var data = data.d.results[0]['slot' + i];
// get the correct div based on the id and then
// set its text to the value
$(divId).text(data);
}
You could try the forEach method, or as already mentioned, get rid of the quotes in "data.d.results[0].slot"
var data = [{
"id": 1,
"Name": "Some Title 1",
"number": "Number 1"
}, {
"id": 2,
"Name": "Some Title 2",
"number": "Number 2"
}, {
"id": 3,
"Name": "Some Title 3",
"number": "Number 3"
}];
//data.d.results[0] << you'd use this
data.forEach(elem => {
document.getElementById("entries").innerHTML += elem.Name +"<br/>";
});
<div id="entries"></div>

Procedure to add element to JSON array

I have been trying to add an element to a JSON array, in which the JSON array is designed with the following attributes:
/*
var courses = [{
"dept": "CSC",
"id": "3102",
"instructor": "Kooima",
"Location": "230 Turead"
}
]
and the JavaScript code segment that performs the task is implemented as:
var newCourse = {};
courses.push(newCourse);
var count = courses.length - 1;
courses[count].dept = dept;
courses[count].id = num;
courses[count].instructor = prof;
courses[count].Location = loc;
However, I believe this may not be in the correct order/missing further code to properly add the element to the list, and wanted to make sure I was possibly not neglecting an essential component.
What you did will work fine. Personaly I prefer the following way;
var newCourse = {};
newCourse.dept = dept;
newCourse.id = num;
newCourse.instructor = prof;
newCourse.Location = loc;
courses.push(newCourse);
There is nothing like JSON array, It's simple javascript array which you can create in the following manner.
Just push the new course every time
courses.push({
"dept": dept,
"id": id,
"instructor": prof,
"Location": loc
});
Quick and simple
courses.push({
"dept": dept,
"id": num,
"instructor": prof,
"Location": loc
});

What is the best way to get a property value from all json-ld objects on a page?

I'm trying to pull all the mpn values from a product results page, where the data is stored in JSON-LD format. Grabbing the top 10 values, is this the most ideal way to do it?
(function(){
var mpns= document.querySelectorAll('script[type="application/ld+json"]');
var x = [];
mpns.forEach(
function(value){
var a = JSON.parse(value.innerText).mpn;
x.push(a);
}
);
return x.slice(0,10);
})();
<script type="application/ld+json">
{
"#context": "http://schema.org/",
"#type": "Product",
"name": "Executive Anvil",
"image": "http://www.example.com/anvil_executive.jpg",
"description": "Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height.",
"mpn": "925872",
"brand": {
"#type": "Thing",
"name": "ACME"
}
}
}
</script>
no it's not good way . because if mpns array iength is in terms of 1000000 then what is the meaning of push if you want only first 10 element .
so try for loop instead

Read JSON data from javascript and trim string

I have json file like this,
{
"data":{
"type": "runjob",
"id": "1",
"inputs": [
{
"name": "input",
"value": "d:\\My\\filestore\\JMJ\\Content\\input.xml"
},
{
"name": "cmd",
"value": "test.js //NoLogo"
},
{
"name": "output",
"value": "d:\\My\\filestore\\JMJ\\Content\\output.xml"
}
],
"disabled": false
}
}
I need to read the velues, input.xml and output.xml using javascript.. How can I get those value?
var stdin = WScript.StdIn.ReadAll();
var json = eval('(' + stdin + ')');
var log = new Log(json.data.inputs[?]);
json.data.inputs is an array (note it's json; as Tushar pointed out, you have had jason in the question). So you can use any technique for accessing or looping through an array that's supported by your environment. It look slike you're using JScript on Windows Script Host; last I checked it didn't even have ES5 features, so perhaps a simple for loop:
var i;
var inputs = json.data.inputs;
for (i = 0; i < inputs.length; ++i ){
// Here, inputs[i].name will be the name ("input", "cmd", "output")
// and inputs[i].value will be the value ("d:\\My\\filestore\\JMJ\\Content\\input.xml", for instance)
}
json.data.inputs is an array containing 3 json objects; you want the value property of the first and the third elements:
json.data.inputs[0].value; // "d:\\My\\filestore\\JMJ\\Content\\input.xml"
json.data.inputs[2].value; // "d:\\My\\filestore\\JMJ\\Content\\output.xml"

How to extract data from this JSON string?

I'm new to JSON and Jquery, and I can't find how to extract the values of ProjectCode from this JSON string.
[
{
"ProjectID": 3,
"CLustomerCode": "XYZ001",
"ProjectCode": "YZPROJ1",
"Description": "Project1",
"IssueManager": "iant",
"NotificationToggle": false,
"ProjectStatus": null,
"Added": "/Date(1400701295853}/",
"Added By": "iant",
"Changed": "/Date(1400701295853)/",
"Changed By": "iant"
},
{
"ProjectID": 4,
"CustomerCode": "XYZ001",
"ProjectCode": "XYXPROJ2",
"Description": "Projecton:Project2",
"IssweManager": "iant",
"NotificationToggle": false,
"Projectstatus": null,
"Added": "lDate(1400701317980)/",
"AddedBy": "iant",
"Changed": "/Date(1400701317980)/",
"Changed By": "iant"
}
]
The string above is from a variable called data that is the return value from stringify. I expected to be able to do something like
string proj = data[i].ProjectCode;
but intellisense doesn't include any of the properties.
I know very little about JSON - any help appreciated.
Thanks for reading.
Use parseJSON:
var obj = jQuery.parseJSON("{ 'name': 'Radiator' }");
alert(obj.name);
You need to loop through each object returned in the response and get the ProjectCode property inside each one. Assuming the data variable is your JSON this should work:
$.each(data, function(i, obj) {
console.log(obj.ProjectCode);
});
Use JSON.parse():
var a; // Your JSON string
var b = JSON.parse(a); //Your new JSON object
//You can access Project code, use index i in b[i].ProjectCode in a loop
var projectCode = b[0].ProjectCode;
You should post the raw code so its easier to visualize this stuff. Since what you are looking for is the list of ProjectCodes (in this case - ["XYZPROJ1", "XYZPROJ2"]).
It seems like what we have is an array or list ([...]) of projects. Where each project has a ProjectID, CustomerCode, ProjectCode, Description and so on...
So lets assume data points at this JSON blob. Here is how you would go about accessing the ProjectCode:
// Access the "i"th project code
var p_i_code = data[i].ProjectCode;
// How many projects?
var num_projects = data.length; // since data is a list of projects
// Want the list of project codes back? (I use underscore.js)
var project_codes = _.map(data, function(project) {
return project.ProjectCode;
});

Categories

Resources