I am working on a script in Google Sheets to import JSON data via API and need to be able to parse the data into columns in a spreadsheet. The API is returning a multi-dimensional array with a key that is a randomly generated ID.
{
"log":{
"5DUA3NAuET1O7TDhIvmC":{
"log":4440,
"title":"Trade money outgoing",
"timestamp":1649773788,
"category":"Trades",
"data":{
"user":282048,
"trade_id":"[view]",
"money":39562944
},
"params":{
}
}
}
}
How can I
Parse the data into a multidimensional object
Access the values like title, data.cost, etc to be able to import this data to a sheet?
Try
var result = []
function test(){
jsonString = `{
"log":{
"5DUA3NAuET1O7TDhIvmC":{
"log":4440,
"title":"Trade money outgoing",
"timestamp":1649773788,
"category":"Trades",
"data":{
"user":282048,
"trade_id":"[view]",
"money":39562944
},
"params":{
}
}
}
}`
let json= JSON.parse(jsonString.replace(/(\r\n|\n|\r|\t| )/gm,""))
getMyData(json)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('test').getRange(1,1,result.length,result[0].length).setValues(result)
}
function getMyData(obj) {
for (let p in obj) {
if (obj[p]!=null){
if (typeof obj[p] != 'object' && typeof obj[p] != 'function'){
result.push([p, obj[p]]);
}
if (typeof obj[p] == 'object') {
result.push([p, '']);
getMyData( obj[p] );
}
}
}
}
var response = {
"log": {
"5DUA3NAuET1O7TDhIvmC": {
"log": 4440,
"title": "Trade money outgoing",
"timestamp": 1649773788,
"category": "Trades",
"data": {
"user": 282048,
"trade_id": "[view]",
"money": 39562944
},
"params": { }
}
}
}
var key = Object.keys(response.log)[0];
console.log(key);
var obj = response.log[key];
console.log(obj.title);
console.log(obj.data.user);
Related
I have this function:
fun getFeed(token: String): Result<Array<Post?>, Exception> {
if (token != "") {
val (request, response, result) = "https://alles.cx/api/feed"
.httpGet()
.header("Authorization", token.toString())
.response()
when (result) {
is Result.Success -> {
println("Result success")
try {
val responseJSON = JSONObject(String(response.data))
if (!responseJSON.has("err")) {
println("Has no error")
var feedArray = arrayOfNulls<Post>(0)
println("HERE?")
var feed = JSONArray(responseJSON["feed"]) // <-----ERROR HERE
println("not here")
println("Made to the for")
for (i in 0 until feed.length()) {
println("For $i")
val jsonObject = feed.getJSONObject(i)
var imageURL: URL? = null
if (jsonObject.has("image")) {
imageURL = URL(jsonObject["image"].toString())
}
feedArray[i] = Post(
jsonObject.getString("id"),
User(jsonObject.getJSONObject("author").getString("id"), jsonObject.getJSONObject("author").getString("username"), jsonObject.getJSONObject("author").getString("name")),
jsonObject.getString("createdAt"),
jsonObject.getInt("replyCount"),
jsonObject.getInt("score"),
jsonObject.getString("content"),
null,
imageURL,
jsonObject.getInt("vote")
)
println("Added post $i")
}
println(feedArray)
return Result.Success(feedArray)
}
else {
println("yes error")
return Result.Failure(Exception(responseJSON["err"].toString()))
}
}
catch(e: Exception) {
return Result.Failure(e)
}
}
is Result.Failure -> {
return Result.Failure(Exception(result.component2()?.localizedMessage))
}
}
}
else {
return Result.Failure(Exception("badAuth"))
}
}
An error is occurring on this line. I know this because of the print statements that are in the code:
var feed = JSONArray(responseJSON["feed"]) // <-----ERROR HERE
This is what the error that is occurring is.
[Failure: org.json.JSONException: Not a primitive array: class org.json.JSONArray]
This is what the feed object from the get request will look like, just so you have an idea of what it is:
{
"feed": [
{
"type": "post",
"slug": "equ2ZfaX2UThtkS8DzkXdc",
"author": {
"id": "00000000-0000-0000-0000-000000000000",
"name": "Archie",
"username": "archie",
"plus": true
},
"content": "I know it's quite inactive here atm. But I'm doing tons of stuff behind the scenes - basically rewriting the entire platform from scratch. Micro will be done by the end of the summer.",
"image": null,
"createdAt": "2020-07-30T20:39:23.000Z",
"score": 5,
"vote": 0,
"replyCount": 0,
"hasParent": false
}
]
}
What could possibly be going wrong here. I am using Fuel for the request, but I don't think that is the problem
Pretty sure the correct way to get the array would be to do var feed = responseJSON.getJSONArray("feed"). You're implementation calls the JSONArray(Object o) constructor which is meant to be called only for primitive arrays (int[], double[], etc.) as they cannot be effectively typed using generics). Thus the constructor complains as you pass in an object which is not a primitive array.
I want to retrieve a specific data from my object stored in local storage using angular. Here is my Object:
{
"user":{
"login":"lara",
"grade":"A"
},
"profiles":[
{
"profile":"admin",
"application":"management",
}
]
}
I want to retrieve profile information (admin) from the list of profiles.
I tried using localStorage.getItem().
setItem in local storage
const data = { your data object here }
SET ITEM
localStorage.setItem("data", JSON.stringify(data));
GET ITEM
let val = JSON.parse(localStorage.getItem('data')).profiles[0].profile;
console.log({val});
You can try with this solution
let data = {
"user": {
"login": "lara",
"grade": "A"
},
"profiles": [
{
"profile": "admin",
"application": "management",
}
]
}
for set data in local storage
localStorage.setItem("data", JSON.stringify(data));
for getting data from local storage
let val = JSON.parse(localStorage.getItem('data'));
if (val) {
let adminProfile = val.profiles.find((data) => data.profile == "admin");
console.log(adminProfile);
}
Try by this..
Use this while storing:
var data = {
"user":{
"login":"lara",
"grade":"A"
},
"profiles":[
{
"profile":"admin",
"application":"management",
}
]
}
localStorage.setItem("data", JSON.stringify(data));
while getting:
let val = JSON.parse(localStorage.getItem('data'));
let profile = val.profiles[0].profile;
I made an http request and got back e.g the below json. I want to read the cars and the shoes objects into separate arrays at the time of the http request.
json
{
"id": 9,
"name": "Zlatan",
"cars": [
{
"type": "ford",
"year": "2019"
},
{
"type": "audi",
"year": "2017"
}
]
"shoes": [
{
"brand": "adidas",
"status": "old"
},
{
"brand": "timberland",
"status": "new"
}
]
}
comp.ts
cars = [];
shoes = [];
//......
getZlatan() {
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars ....//what to add here
this.shoes ....// here too.
} );
}
Or is there a cleaner way to load the arrays at http request?
Access the cars and shoes properties of the data with simple dot-notation. It might be ideal to check if the data returned is not null with if(condition here) and then perform your logic. If you have more objects and want to bring all cars and shoes under one array then you have to loop through.
getZlatan() {
return this.httpService.getInfo()
.subscribe(data => {
this.objZlatan = data;
this.cars = this.objZlatan.cars;
this.shoes = this.objZlatan.shoes;
});
}
Just use . and type names to access cars and shoes. Let me show an example:
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars = data.cars;
this.shoes =data.shoes;
} );
I have a http.post request which sends an object as a parameter, the expected format is like this:
var searchQuery;
var subj;
var body;
var startDate;
var endDate;
{
"search": {
"scope": [2,3,32],
"type": "basic",
"text": {
"value": searchQuery, //string variable coming from UI
"fields": [
subj, body //string variable coming from UI
]
},
"date": {
"type": "range",
"from": startDate, //string variable coming from UI
"to": endDate //string variable coming from UI
}
The problem is some values are optional meaning that if I don't provide searchQuery as a string then the whole key value should be ingnored, e.g "value": searchqery should be not included in the json object if I did not provide value to that variable. Same goes for startDate and endDate if I don't provide values then date shouldbe ignored from the json.
So how to dynamically include or exlude key pair value in the object that coming from UI and how to build that object before sending to a post request?
Whould it be something like this?
var search = {};
search.text = { value: "", fields: [] };
{value: "", fields: Array(0)}
seach.text.value = "wes";
search.text.value = "wes";
search.text.fields.push("subject");
search.text.fields.push("body");
You can create a function that's a bit more flexible.
var searchQuery = "";
var subj = null;
var body = "";
var startDate = "";
var endDate = null;
let obj = {
"search": {
"scope": [2, 3, 32],
"type": "basic",
"text": {
"value": searchQuery, //string variable coming from UI
"fields": [
subj, body //string variable coming from UI
]
},
"date": {
"type": "range",
"from": startDate, //string variable coming from UI
"to": endDate //string variable coming from UI
}
}
}
function removeNull(obj) {
return Object.keys(obj).reduce((res, key) => {
if (Array.isArray(obj[key])) {
// If it's an array, filter out the null items
res[key] = obj[key].filter((item) => item != null && item !== "");
} else if (typeof obj[key] === "object" && obj[key] != null) {
// If it's an object, call the function recursively
res[key] = removeNull(obj[key]);
} else if (obj[key] != null && obj[key] !== "") {
// Otherwise, only add it to the results if it's not null
res[key] = obj[key];
}
return res;
}, {});
}
console.log(removeNull(obj));
I want to get the translatedText value. But in the console.log keep show undefined. w
this.getPosts('Hello', 'ja');
getPosts(text, category) {
this.translateService.getPosts(text, category).subscribe(response => {
console.log(response.data.translations.translateText);
this.items = response.data.translations;
console.log(items.translateText)
}
Here's the Json Format.
{
"data": {
"translations": [
{
"translatedText": "Hallo Welt",
"detectedSourceLanguage": "en"
}
]
}
}