JSON data to Google sheet - javascript

I have a JSON link who is giving me data like -
"data": [{
"name": "123Seguro",
"domain": "123seguro.com",
"id": 1,
"slug": "123seguro"
}, {
"name": "Earn.com",
"domain": "21.co",
"id": 2,
"slug": "earn-com"
}, {
"name": "2C2P",
"domain": "2c2p.com",
"id": 3,
"slug": "2c2p"
}, {
"name": "4thWay",
"domain": "4thway.co.uk",
"id": 5,
"slug": "4thway"
}, {
"name": "51credit.com",
"domain": "51credit.com",
"id": 6,
"slug": "51-credit-card-manager"
}, ........................................
Is there is a way to take these data to Google sheet in 4 columns as it is giving 4 column data?
I tried with a script like this -
function fetch() {
var response = UrlFetchApp.fetch('mylink.json');
var res1 = response.getContentText();
var json = JSON.parse(res1);
var name = json["name"];
Logger.log(name);
}
But it is not reading the data and logger returning "UNDEFINED". can somebody help here, please.
Edit-1
On a small research, I found a script like this -
function IMPORTJSON(url,xpath){
try{
// /rates/EUR
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
var json = JSON.parse(content);
var patharray = xpath.split("/");
//Logger.log(patharray);
for(var i=0;i<patharray.length;i++){
json = json[patharray[i]];
}
//Logger.log(typeof(json));
if(typeof(json) === "undefined"){
return "Node Not Available";
} else if(typeof(json) === "object"){
var tempArr = [];
for(var obj in json){
tempArr.push([obj,json[obj]]);
}
return tempArr;
} else if(typeof(json) !== "object") {
return json;
}
}
catch(err){
return "Error getting data";
}
}
Here I am applying the formula like this - =IMPORTJSON("https://theAPILINK.json","data")
And the response is like
0
1
2
3
4
.
.
.......And at the moment I am changing from "data" to "name" it is showing "Node Not Available".
Any suggestions, please. :)

First of all it's important to understand your JSON data structure:
Data
-> 0
-> -> Name: 123Seguro
-> -> Domain: 123seguro.com
-> -> id: 1
-> -> slug: 123seguro
-> 1
-> -> Name: Earn.com
-> -> Domain: 21.co
-> -> id: 2
-> -> slug: earn-com
-> 2
....
So to reach your data, you'll always need to first open data and then select a specific "row".
function fetch() {
var response = UrlFetchApp.fetch('mylink.json');
var res1 = response.getContentText();
var json = JSON.parse(res1);
var name = json["name"];
Logger.log(name);
}
But it is not reading the data and logger returning "UNDEFINED". can somebody help here, please.
This is because you first need to open data as explained above. Then define the item of which you want to know the name. Try something like Logger.log(json["data"][0]["name"]). This should return the name of the first item in your JSON response.
Here I am applying the formula like this - =IMPORTJSON("https://theAPILINK.json","data") And the response is like 0 1 2 3 4 . . .......And at the moment I am changing from "data" to "name" it is showing "Node Not Available".
So you tell the function where to find your data and the root node (data). When you change data to name it is unable to find an element called like that. So it will return the error you've mentioned.
I would recommend to dive into your first fetch example instead of using the other function. It'll help you to understand the mechanism and process the data as you require.

Related

Editing JSON files in NodeJS and DiscordJS

Right, so I am trying to wrap my head around editing (appending data) to a JSON file.
The file (users.json) looks like this:
{
"users": {
"id": "0123456789",
"name": "GeirAndersen"
}
}
Now I want to add users to this file, and retain the formatting, which is where I can't seem to get going. I have spent numerous hours now trying, reading, trying again... But no matter what, I can't get the result I want.
In my .js file, I get the data from the json file like this:
const fs = require('fs').promises;
let data = await fs.readFile('./test.json', 'utf-8');
let users = JSON.parse(data);
console.log(JSON.stringify(users.users, null, 2));
This console log shows the contents like it should:
{
"id": "0123456789",
"name": "GeirAndersen"
}
Just to test, I have defined a new user directly in the code, like this:
let newUser = {
"id": '852852852',
"name": 'GeirTrippleAlt'
};
console.log(JSON.stringify(newUser, null, 2));
This console log also shows the data like this:
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
All nice and good this far, BUT now I want to join this last one to users.users and I just can't figure out how to do this correctly. I have tried so many version and iterations, I can't remember them all.
Last tried:
users.users += newUser;
users.users = JSON.parse(JSON.stringify(users.users, null, 2));
console.log(JSON.parse(JSON.stringify(users.users, null, 2)));
console.log(users.users);
Both those console logs the same thing:
[object Object][object Object]
What I want to achieve is: I want to end up with:
{
"users": {
"id": "0123456789",
"name": "GeirAndersen"
},
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
}
When I get this far, I am going to write back to the .json file, but that part isn't an issue.
That's not really a valid data structure, as you're trying to add another object to an object without giving that value a key.
I think what you're really looking for is for 'users' to be an array of users.
{
"users": [
{
"id": "0123456789",
"name": "GeirAndersen"
},
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
]
}
You can easily create an array in JS and the push() new items into your array. You JSON.stringify() that with no issue.
const myValue = {
users: []
};
const newUser = {
'id': '0123456789',
'name': "GeirAndersen'
};
myValue.users.push(newUser);
const strigified = JSON.stringify(myValue);

Applying JSON.parse() to unusual JSON file

Trying to access the value field of this JSON file using JSON.parse() in Meteor, but I cannot get it to return anything. I suspect there is an error in my syntax in selecting the data from the imported JS object.
{"status":"success","data":{"subjects":[{"value":"ABC","descr":"Descriptions"}]},"message":null,"meta":{"copyright":"Copyright","referenceDttm":"Date"}}
I'm trying to store it into an array, subjectArray. This is the code I'm using:
var subjectArray = new Array();
subjectFile = HTTP.get("https://classes.cornell.edu/api/2.0/config/subjects.json?roster=FA15");
subjectJSON = JSON.parse(subjectFile);
for (int i=0; i<subjectJSON.length; i++) {
subjectArray.push(subjectJSON[i].value)
}
Pretty printed this is:
{
"data": {
"subjects": [
{
"descr": "Descriptions",
"value": "ABC"
}
]
},
"message": null,
"meta": {
"copyright": "Copyright",
"referenceDttm": "Date"
},
"status": "success"
}
Responses from HTTP calls can take a while to come back so you should read your replies in an async way. You should move all of your code related to the "get" inside a callback function. If you want to find out more about HTTP and callbacks in Meteor make sure you check the docs
If you know what "value" is in your for loop ('cause I don't), then this is your answer:
HTTP.get("https://classes.cornell.edu/api/2.0/config/subjects.json?roster=FA15", function (err, res) {
if(!!err) return false;
subjectJSON = JSON.parse(res);
for (var i = 0; i < subjectJSON.length; i++) {
subjectArray.push(subjectJSON[i].value);
}
return true;
});
Also, there is no int in JavaScript.

Converting mysql exported json object to a properly formatted javascript array of objects

Have got a json file exported from mysql. One particular line is not a well represented json object, i'm trying to convert this to a proper array of object.
var data = "{"54":
{"ID":"54",
"QTY":"1",
"NAME":"Large",
"TOTAL":1.86
},
"TOTAL":10.54,
"313":
{"ID":"313",
"QTY":2,
"NAME":"Quater Pounder",
"TOTAL":8.68
}
}"
//and wants to make it:
var data = [
{"ID" : "54",
"QTY" : "1",
"NAME": "Quarter Pounder",
"TOTAL": 8.68
},
{"ID":"313",
"QTY":2,
"NAME": "Quater Pounder",
"TOTAL":8.68
}
]
I was able to fix this by using angular.forEach(response, function(item){}), I then created a childArray, which I pushed the result of the above into.
Please see code:
angular.forEach( $scope.response, function (item) {
item.childrenList = [];
angular.forEach( JSON.parse( item.details ), function (value, id) {
item.childrenList.push( value );
})
});

Update JSON with jquery error

I'm trying to update a JSON file with the value of a textarea using jquery push. I'm receiving the following error: " JavaScript runtime error: Unable to get property 'push' of undefined or null reference"
My jquery:
function submittedMsg(ctx) {
var id = $('.msg-input form').attr('id');
var newMsg = $('.msg-input textarea').val();
var url = "/ajax.aspx?vtl=ajax-conversation-json&cv=" + id;
$.getJSON(url, function (messageString, message) {
var message = [];
message.push({
msgcontent: newMsg,
sendname: sendRname,
mbrhref: mbrUrl,
datetime: ""
});
});
}
My JSON:
{
"messageString" :
[
{ "subject": "hello",
"msgstring": "5",
"unread": "1",
"datetime": "Oct 1 2013 9:59PM",
"orderid": "17",
"recipient": [
{
"mbrname": "Jane Doe",
"mbrhref": "/profile.aspx?mem=1227"
},
{
"mbrname": "John Smith",
"mbrhref": "/profile.aspx?mem=1337"
}
],
"message": [
{
"datetime":"2013-10-01T21:59:33.063",
"sendname":"Jane Doe",
"mbrhref":"/profile.aspx?mem=1227",
"msgcontent": "<p>Hi. I would like to talk with you about Dwarf Beryl Beauty</p>"
},
{
"datetime":"2013-11-26T16:29:17.037",
"sendname":"John Smith",
"mbrhref":"/profile.aspx?mem=1337",
"msgcontent": "Tough luck."
}
]
}
]
}
I don't necessarily need to use push to update the JSON file if there is a better way, I'm open to suggestions. I've verified my URL path is correct. Am I just missing something obvious? I'm new to JSON and only have passable jquery skills. Help!
Thanks in advance for any direction.
Try to use:
data.message.push
instead of:
data.messageString.message.push
Ah I see the issue, you have a local var and parameter of the same name message:
$.getJSON(url, function (messageString, message) { //here is param message
var message = []; //here is a local var parameter
message.push({ //this is probably referencing the parameter which is not an array or object that supports .push
Instead:
$.getJSON(url, function (data) { //I renamed the param to be more consistent with documentation, although it doesn't really matter, just will generate confusion
data.messageString.push({ //modify the json we were passed in the data param

How to manipulate JSON object to remove root key within Javascript?

I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});

Categories