How to retrieve data from json file - javascript

I am having trouble with accessing my json file from my javascript file. I would like to change the object to a different text in my json file once a submit button is clicked on the webpage. I am aware that I would use ajax to achieve this goal, but I do not know how to access the json file.
This is the db.json file
{
{
"assets": [
{
"id": "0946",
"manufacturer": "SONY",
},
{
"id": "0949",
"manufacturer": "AUDIOTECNIA"
}
],
"transfers": [
{
"id": 1,
"status": "in-progress"
}
]
}
This is my Javascript file
$('form').on('submit', function(e){
e.preventDefault();
parsedData = JSON.parse(db.json);
console.log(parsedData[0].id)
//Changing Status
$.ajax({
type: "PATCH",
url: `http://localhost:3000/transfers/`
});
I've tried using parseData because I read that is how to retrieve the object, from the json file, but I do not believe I am writing it correctly. What documentation or steps would one recommend for solving this issue?

You have an extra comma after "in-progress",
const parsedData = JSON.parse(`{
"transfers": [ {
"id": 1,
"status": "in-progress"
}]
}`)
Then, to access id in parsedData:
console.log(parsedData.transfers[0].id)

You did not initialize the variable parsedData.
var parsedData = JSON.parse(db.json);

Related

JSON, Highcharts and Coldfusion json data

I have been trying to make this work for sometime and its I cannot seem to find the solution to make this work.
I am able to output JSON with my coldfusion CFC without issue, not I am trying to use this JSON with Highcharts.js. I have verified that the JSON is valid but highcharts seems to have an issue because in the series data there is double quotes surrounding the data. I've looked everywhere for a solution and I cannot seem to find any help that can set me on the right path. If I remove the double quotes from around the array in the series.data the chart loads in fine but I get away from it being dynamic.
Here is my JSON output from my CFC:`
{
"series": [{
"data": "[[Date.UTC(2017,05,21),2.9],[Date.UTC(2017,05,28),2.9],[Date.UTC(2017,06,04),3.1],[Date.UTC(2017,06,11),2.9]]",
"name": "ATC Main Pod A - B - C"
}, {
"data": "[[Date.UTC(2017,05,21),2.8],[Date.UTC(2017,05,28),2.6],[Date.UTC(2017,06,04),2.9],[Date.UTC(2017,06,11),2.9]]",
"name": "ATC Mays (ACB Blue)"
}, {
"data": "[[Date.UTC(2017,05,21),2.4],[Date.UTC(2017,05,28),2.6],[Date.UTC(2017,06,04),3],[Date.UTC(2017,06,11),3.2]]",
"name": "ATC Mays (ACB Purple)"
}, {
"data": "[[Date.UTC(2017,05,21),3.3],[Date.UTC(2017,05,28),3.3],[Date.UTC(2017,06,04),3.4],[Date.UTC(2017,06,11),3.3]]",
"name": "ATC R10 Pod D"
}, {
"data": "[[Date.UTC(2017,05,21),3.3],[Date.UTC(2017,05,28),3.4],[Date.UTC(2017,06,04),2.8],[Date.UTC(2017,06,11),1.9]]",
"name": "ATC TU Pod A - B"
}, {
"data": "[[Date.UTC(2017,05,21),2.9],[Date.UTC(2017,05,28),2.9],[Date.UTC(2017,06,04),3.1],[Date.UTC(2017,06,11),3.4]]",
"name": "CTRC 1st Floor"
}, {
"data": "[[Date.UTC(2017,05,21),2.9],[Date.UTC(2017,05,28),3.3],[Date.UTC(2017,06,04),3.2],[Date.UTC(2017,06,11),2.3]]",
"name": "CTRC 2nd Floor"
}]
}
Here is what my ajax call looks like:
function loadChartData(c){
$.ajax({type: "POST", url: "CFCs/survey.cfc", data: {method:"results_RLU", CENTERID: c},dataType: 'json',success: function(data){
options.series = data.series
var chart = new Highcharts.Chart(options)
}
});
}
Not a problem!
Simply iterate each item in the series and parse the data to valid JSON object.
Enjoy :)
function loadChartData(c){
$.ajax({type: "POST", url: "CFCs/survey.cfc", data: {method:"results_RLU", CENTERID: c},dataType: 'json',success: function(data){
options.series = data.series.map(function(item)
{
item.data = JSON.parse(item.data);
return item;
});
var chart = new Highcharts.Chart(options)
}
});
}

Javascript/Jquery push json objects into array

I have an json object coming from a $.post in jquery.
In order to loop through and store the data clientside I would like to add it to an array. For each search results that comes back I would like to "append" the array so it grows.
This is my json:
{
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
} ]
}
This is what I have come up with so far were data is the json
comming back fron the post ajax request. Obj is just an object holding the array
which I declared further up in my code. obj.companies = new Array();
obj.companies.push(data['companies']);
The next part I need to loop out the array. Trying to do it like this.
$.each(obj.companies, function(i, item) {
// Does not alert correctly.
alert(item.header);
});
So I need to push the full json object into the array. But I cannot alert the item.header within the loop, how can I accomplish this?
EDIT:
Thanks everyone. Sorry if my question wasnt detailed enough.
I ended up doing this:
getcompanies: function() {
obj = this;
$.post('api/finder/result.php', {}, function(data) {
$.each(data.companies, function(i, item) {
obj.companies.push(item);
});
obj.loadcompanies();
}, "json");
},
loadcompanies: function() {
$.each(this.companies, function(i, item) {
alert(item.header);
}
}
I believe there is a issue with your server side code which is responsible for building JSON object which is getting returned via Ajax. The Correct JSON should be as follows:
{
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
}
]
}
Please note that there is only single key with name "companies" which holds an array of objects. Please correct your server side code to get such valid JSON. You can use free online JSON validator tools such as http://jsonlint.com/ to validate your JSON objects.
Now once you get such response from server; you just need to do following steps to get the companies array (following code will go into $.post success handler):
var jsonResp = JSON.parse(postResponse); //postResponse is the success resp of $.post
var companiesArray = jsonResp.companies;
$.each(companiesArray , function (index, valueObj){
var compId = valueObj.companyid;
var isSaved = valueObj.saved;
});
I hope this will help you a bit.
if you want to append new company into your companies array you should
var json_obj = {
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
} ]
};
//adding new company into your companies array
json_obj.companies.push({
"companyid":"117",
"saved" : false,
"orgnumber": "20120313",
"companyname":"anotherCompany",
"header":"another header info"
});
//if you want to loop through your companies list you can:
json_obj.companies.map(function ( obj ){
console.log(obj.companyid);
console.log(obj.companyname);
etc..
});

Return JSON results as JS array with AJAX?

Apologies in advance - I am new to this and so other answers have not been able to help me.
I have used AJAX to send data to a PHP script (part of a 3rd party API). The PHP script returns the results as JSON, but I have no idea how to format these on my HTML page.
Ultimately, I would like to save the JSON results as an array and then use JS/Jquery to format them on the page.
I am not sure how to modify the PHP and AJAX scripts to achieve this. Can anyone point me in the right direction?
My AJAX:
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
success: function(data) {
<!--NOT SURE WHAT TO PUT HERE-->
}
})
PHP (after the calculator does its thing - not sure if it needs to be changed):
$serviceTypesJSON = json_decode($rawBody);
echo json_encode($serviceTypesJSON);
The expected JSON results should look like:
{
"services": {
"service" : [
{
"code": "AUS_PARCEL_REGULAR",
"name": "Parcel Post (your own packaging)",
"speed": 2,
"price": 6.95,
"max_extra_cover": 5000,
"extra_cover_rule": "100,1.5,1.5",
"icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
"description": "Based on the size and weight you've entered",
"details": "Check our ",
"delivery_time": "Delivered in up to 3 business days",
"ui_display_order": 1,
"options": {
"option": [
{
"code": "AUS_SERVICE_OPTION_STANDARD",
"name": "Standard Service",
"price": "0.00",
"price_type": "static",
"option_type": "optional",
"ui_display_order": 1
},
{
"code": "AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY",
"name": "Signature on Delivery",
"price": 2.95,
"price_type": "static",
"option_type": "optional",
"tooltip": "Signature on Delivery provides you with the peace of mind that your item has been delivered and signed for.",
"ui_display_order": 2,
"suboptions": {
"option": {
"code": "AUS_SERVICE_OPTION_EXTRA_COVER",
"name": "Extra Cover",
"option_type": "optional",
"price_type": "dynamic",
"tooltip": "Extra Cover provides cover for loss, damage or theft of your item and will fully compensate you to the value specified for your item.",
"ui_display_order": 1
}
}
}
]
}
},
You can do two things, if the return data is JSON use dataType: "json" in the AJAX call.
Edit 1
If you are using dataType: "json". Which is more preferred if you are sure the data return is JSON string. data variable in the success will directly give you the JSON object. I think you can access it like data['services'].
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services;
}
Or you can just get the data then use jQuery.parseJSON() to parse the data string into JSON object.
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {
toPostcode: toPostcodeValue,
parcelLengthInCMs: parcelLengthInCMsValue,
parcelHeighthInCMs: parcelHeighthInCMsValue,
parcelWidthInCMs: parcelWidthInCMsValue,
parcelWeightInKGs: parcelWeightInKGsValue
},
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services; //or jsonObj["services"]
}
})
Your success function will never be called if you are using
echo json_encode(); in your php script.
You should add dataType:'json' after type:'POST' and then your success function will get called and will get the result returned by server in data

invalid character javascript error while using JSON.parse

I am trying to convert a json string to object format read from a .js file.
Below is the JSON string in document.js
[
{
"type": "TableShape",
"id": "63c0f27a-716e-804c-6873-cd99b945b63f",
"x": 80,
"y": 59,
"width": 99,
"height": 107,
"name": "Group",
"entities": [
{
"text": "id",
"id": "49be7d78-4dcf-38ab-3733-b4108701f1"
},
{
"text": "employee_fk",
"id": "49be7d78-4dcf-38ab-3733-b4108701fce4"
}
]
}
];
now i am calling the document.js in window load using AJAX like below
$(window).load(function () {
$.ajax({
url: "JS/Draw2d/SampleData/document.js",
async: false,
success: function (result) {
debugger;
jsonStringFromServer = JSON.parse(result);//Here Javascript error stating invalid character
alert(jsonStringFromServer);
}
});
});
When the $.ajax function receives JSON, it automatically deserialises it for you. The error you're seeing is being cause because you're passing an object to JSON.parse, not a JSON formatted string - you don't need to use JSON.parse at all. Try this:
success: function (result) {
debugger;
console.log(result); // = the received object
}
I would also strongly suggest you remove async: false as it is extremely bad practice to use it.

display json data using xhrget (DOJO)

I am unable to figure out what is the problem with displaying json data..below is the code
var xhrGet1 = dojo.xhrGet({
url: "Page/",
handleAs: "json",
handle: function(response)
{
dojo.byId('json-data').innerHTML = response.questions[0];
}
});
Html
<div id='json-data'></div>
And my json file looks like this
{
"Info": {
"PURPOSE": ".... ",
},
"questions": [
{
"ID": 1,
"Question": "User ID",
"Information": "",
}, {
"ID": 2,
"Question": "Name",
"Information": "",
}
],
so on...any ideas??
The property handleAs : "json" in your xhr call makes the incoming json automatically eval'ed to javascript objects. So, you have to convert your javascript object back to string using JSON.stringify.
e.g. :
dojo.byId('json-data').innerHTML = JSON.stringify(response.questions[0]);
You can also use dojo.toJson for the same purpose. It uses json.stringify but has the benefit of having a second argument ("prettyprint"), allowing you to pretty-print out of the box, like this :
dojo.byId('json-data').innerHTML = dojo.toJson(response.questions[0], true);
wrap your JSON with PRE and CODE tags.
So:
dojo.byId('json-data').innerHTML = "<pre>code>" + response.questions[0] + "</code></pre>";
Also see: Display JSON as HTML for some libraries that can help you pretty-format your JSON when rendering in the browser

Categories