0

I use app script and try to get value from return array by API, this is return array :

this is the full JSON:

   {data=[{first=[[10, 1], [14, 0], [13, 5]}]}

I use this code to get value but not woeking:

var request = UrlFetchApp.fetch(url);
var json = JSON.parse(request);
// this is the code to get value
const value= json.data.first.map(obj => [obj[0]]);

The error is : TypeError: Cannot read property 'map' of undefined

2
  • You're trying to map object before the data from API is loaded. That's why it's undefined. Read about async functions: developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/… Commented Sep 28, 2021 at 13:38
  • If my assumption that the full json is {data=[{first=[[10, 1], [14, 0], [13, 5]]}]} (yours is lacking a single closing square bracket), then use data[0] before accessing first. See my answer below. Commented Sep 28, 2021 at 15:24

3 Answers 3

1

The full json's array you included is not properly closed.

modified it to this instead

{data=[{first=[[10, 1], [14, 0], [13, 5]]}]}

Upon doing that, this code should work.

Code:

function myFunction() {
  var json = {data: [{first: [[10, 1], [14, 0], [13, 5]]}]};
  Logger.log(json)
  // access first array element of data
  var value= json.data[0].first.map(obj => [obj[0]]);
  Logger.log(value)
}

Using data[0]:

output

Using data:

output

Sign up to request clarification or add additional context in comments.

Comments

0

Your data doesn't look like JSON to me:

This works:

function myfunk() {
  const resp = '{"time":1632835594443, "first":[[10, 1], [14, 0.16306, 0], [13, 5]]}';
  const obj = JSON.parse(resp);
  Logger.log(JSON.stringify(obj.first));
}

8:26:36 AM  Notice  Execution started
8:26:37 AM  Info    [[10,1],[14,0.16306,0],[13,5]]
8:26:37 AM  Notice  Execution completed

3 Comments

not working, Return null . this is the full JSON {data=[{first=[[10, 1], [14, 0], [13, 5]}]}
That's not JSON. And my code is not returning anything.
I see the error oky I update that in another place can you checked that pleas: stackoverflow.com/questions/69795163/get-value-from-api-json
0

Show your response

But maybe just

const [first] = json.data || []; // get 0 from array
const values = first.map(obj => [obj[0]])

Or maybe get object property

const { first } = json.data || {}; // get propetry first
const values = first.map(obj => [obj[0]])

3 Comments

Error TypeError: first.map is not a function
Please show result of console.log(json.data);
this is the full JSON {data=[{first=[[10, 1], [14, 0], [13, 5]}]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.