Use generated json object instead d3.json - javascript

I missed a lot of time that to resolve this problem but unlucky. I know how to render d3 tree with external file, but how to do that with generated object. I'm getting Json object thru this code:
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
and have added json to d3.json
treeJSON = d3.json(json, function (error, treeData) {
so whole part of code looks like:
function load() {
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
// Get JSON data
treeJSON = d3.json(json, function (error, treeData) {
the most interesting part is that console log self defined such as right string:
[{"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]}]
but I'm still getting an error:
GET http://localhost:63342/testMerg/%7B%22text%22:%22Alas%22,%22icon%22:%22…SH%22%7D]%7D,%7B%22text%22:%22CDISC%22%7D,%7B%22text%22:%22BRIDG%22%7D]%7D 404 (Not Found)
I've tried to use string method from some example which I found somewhere here:
.then(function (data) {
var json = JSON.stringify(data);
// Get JSON data
treeData = JSON.parse( data );
but got an error
Uncaught SyntaxError: Unexpected token o
so I give up... could anybody help me?

The problem arises because data is an Object and your trying to parse the object. But JSON.parse function expects a string as the parameter.
You can either directly assign treeData = data. (No need for parsing).
Or else you should try stringifying the object and then parse the stringified json.
var json = JSON.stringify(data);
treeData = JSON.parse(json);
var data = {"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]};
//treeData = data;
json = JSON.stringify(data);
console.log(JSON.parse(json));

Related

How to parse large nested json objects?

PasteBin JSON
I would like to get this as Object it says jsonlint is valid but parsing is not anyone help would appreciate
"Data":[{...},{...},] // structure build like this
when i try
JSON.parse(jsonparamter) <-- Uncaught SyntaxError: Unexpected token A in JSON at position 71
at JSON.parse (<anonymous>)
at <anonymous>:1:6
There are multiple levels of JSON encoded data so you will have to create a loop to decode the elements deeper in the JSON nest. Use the below code to see an example of accessing Data.Adress.Value in this dictionary
// set up urls and headers for making HTTP req
corsurl = 'https://cors-anywhere.herokuapp.com/'
jsonurl = 'https://pastebin.com/raw/vuecweML'
headerNames = ['Content-Type','Accept']
headerValues = [ 'application/json', 'application/json']
// Modular get request function that I use
function getRequest (baseRestURL, APIPath, headerNames, headerValues, callback) {
var completeRestURL = baseRestURL + APIPath
console.log('REST API URL: ' + completeRestURL)
var method = 'GET'
var url = completeRestURL
var async = true
var request2 = new XMLHttpRequest()
request2.onload = function () {
console.log('ONLOAD')
var status = request2.status // HTTP response status, e.g., 200 for "200 OK"
console.log(status)
console.log(request2.responseText)
var response = request2.responseText
return callback(response)
}
request2.open(method, url, async)
for (var i in headerNames) {
request2.setRequestHeader(headerNames[i], headerValues[i])
}
request2.send(null)
}
// Our code of interest
getRequest(corsurl, jsonurl, headerNames, headerValues, response => {
parsed = JSON.parse(response).Data //parse our data the first time, and get the data attribute from dictionary
objects = JSON.parse(parsed) // parse a second time ( as data is JSON encoded twice )
selection = JSON.parse(objects[0].Address)[0].Value // parse a third time and select an attribute
document.getElementById('result').innerHTML = selection // Add it to our html to display
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id='result'> Loading </div>

Can't Extract data from JSON returned by Google Place Search API

I'm fetchng some data from Google Place Search API, but I don't know why I'm not able to access data from it. Here is my code below.
getData = (keyword, location, country) => {
let dataURI = `${URI}${keyword}+${location}+${country}${API}`;
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = dataURI
fetch(proxyUrl + targetUrl)
.then((res) => res.json())
.then((data) => {
console.log(data); //reurns JSON data
console.log(data.results); //Returns Undefined
})
.catch((e)=> console.log(`Error! ${e.message}`));
}
When I write console.log(data) This is returning the following
JSON data
but when I do console.log(data.results) this returns Undefined.
I also tried JSON.parse(data) but this gives me an error
Unexpected token o in JSON at position 1
You're getting this
Unexpected token o in JSON at position 1
because Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.
So you should try doing this JSON.parse(JSON.stringify(data));

Sending data from NodeJS to the client by using Ajax calls

I increase a value at the server by running an Ajax call and want to update my UI after doing this
function increaseHitpoints(){
$.ajax({
type: 'GET',
url: 'http://localhost:8888/incHp/2312'
}).done(function (data) {
$("#txtHitpoints").html(data);
});
}
In my app.js I read a JSON file, manipulate the value, write it back to the file and return it to the client
app.get('/incHp/:id', function (req, res) {
var database = './database.json';
fs.readFile(database, 'utf8', function (err, data) { // read the data
var json = JSON.parse(data);
var users = json.users;
var hitpoints;
users.find(u => {
if (u.id === Number(req.params.id)) { // get the user by id
u.hitpoints++;
hitpoints = u.hitpoints;
}
});
json = JSON.stringify(json);
fs.writeFile(database, json, (err) => { // update the JSON file
// -> missing part here <-
});
});
});
what do I have to pass into the missing part if I want to return the new value? The new value would be hitpoints
I tried res.send(hitpoints); but it seems this function wants to return a status code, not a value.
If you send a numerical value, it will be observed as an HTTP response code
https://expressjs.com/en/api.html#res
But you can send your hitpoints as a string res.send(hitpoints.toString())or as json res.send({hits: hitpoints});
Depends on what format you want your response to be. I prefer using JSON. So in JSON case you would do this:
fs.writeFile(database, json, (err) => {
res.status(200).json({yourKey: yourValue});
});
Then you can access the JSON object in your frontend:
$("#txtHitpoints").html(data.yourKey);

How do I parse a json response from a GET request

How do I go about parsing this json response so I can grab the email_address keys and their respective values. it is being returned in this function. I have tried response.content.email_address which just returns undefined. It must be really simple, I just can't seem to parse it properly.
Thanks
function (error, response) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
Json Response
content: '{"meta":{"pagination":{}},"results":[{"id":"1405904834","status":"ACTIVE","fax":"","addresses":[],"notes":[],"confirmed":false,"lists":[{"id":"1395617465","status":"ACTIVE"}],"source":"Site Owner","email_addresses":[{"id":"d39bf7e0-a2f9-11e7-909a-d4ae528442b5","status":"ACTIVE","confirm_status":"NO_CONFIRMATION_REQUIRED","opt_in_source":"ACTION_BY_OWNER","opt_in_date":"2017-09-26T20:32:33.000Z","email_address":"anders#kitson.org"}],"prefix_name":"","first_name":"Anders","middle_name":"","last_name":"Kitson","job_title":"","company_name":"","home_phone":"","work_phone":"","cell_phone":"","custom_fields":[],"created_date":"2017-09-26T20:32:33.000Z","modified_date":"2017-09-26T20:32:33.000Z","source_details":""},{"id":"1474126978","status":"ACTIVE","fax":"","addresses":[],"notes":[],"confirmed":false,"lists":[{"id":"1395617465","status":"ACTIVE"}],"source":"Site Owner","email_addresses":[{"id":"62874c40-a398-11e7-a559-d4ae5292bb50","status":"ACTIVE","confirm_status":"NO_CONFIRMATION_REQUIRED","opt_in_source":"ACTION_BY_OWNER","opt_in_date":"2017-09-27T15:27:34.000Z","email_address":"test#example.com"}],"prefix_name":"","first_name":"","middle_name":"","last_name":"","job_title":"","company_name":"","home_phone":"","work_phone":"","cell_phone":"","custom_fields":[],"created_date":"2017-09-27T15:27:34.000Z","modified_date":"2017-09-27T15:27:34.000Z","source_details":""}]}'
You can use JSON.parse(response)
You can then save it in a variable so you can access the data from there.
function(error, response) {
if (error) {
console.log(error);
} else {
var data = JSON.parse(response);
console.log(data.content.email_address) // This should print the value
};
});
I had to end up doing something like this to get one of the email addresses, so i guess I will have to run a for loop or something to get all of them.
var data = JSON.parse(response.content);
var dataParsed = data.results[0].email_addresses[0].email_address;

Uncaught TypeError: Cannot read property 'total' of undefined

I get a JSON from my response object so I do:
var json = JSON.parse(res.text);
I print the JSON and get JSON back. But when I retrieve the value inside json.body.value.total then it gives this error:
Uncaught TypeError: Cannot read property 'total' of undefined
I have no idea why. I pasted the value that receive from var json and printed on console and was able to retrieve total. But I cannot do it through the code. There is a JSON value total. Its just unable to recognize. On the console, it works but does not work in the code.
I get JSON back from my response object which I retrieve using response.text. I think it needs to change in parsable object but all it returns is undefined
it('returns http 200', function (done) {
chai
.request(baseUrl)
.get('/api/')
.set('Authorization', 'Basic abc')
.query({val:'hey'})
.end(function(err, res) {
expect(res).to.have.status(200);
var json = res.text;
console.log('val: '+ JSON.parse(json.body));
var val = json.body.value.total; //undefined
expect(val.to.be.above(0)); //fails
done();
});
});
The REST API that I built was returning the response.body but what worked is this:
var body = JSON.parse(json.body);
var obj = JSON.stringify(body);
var jsonObj = JSON.parse(obj);
The above looks ridiculous but thats what worked. json -> object -> json. It was finding trouble to figure out that its a json object.
The console was doing a good job but not the library that I was using.
The complete code is this:
it('returns http 200', function (done) {
chai
.request(baseUrl)
.get('/api/')
.set('Authorization', 'Basic abc')
.query({val:'hey'})
.end(function(err, res) {
expect(res).to.have.status(200);
var json = res.text;
var body = JSON.parse(json.body);
var obj = JSON.stringify(body);
var jsonObj = JSON.parse(obj);
var val = jsonObj.body.value.total;
expect(val.to.be.above(0));
done();
});
});
You're not assigning the parsed value to json.
var json = res.text;
should be
var json = JSON.parse(res.text);
You have to put you json string into JSON.Parse() and access the properties on the result of the Parse function.
You can't just access properties from a text.

Categories