I can't reach my returned JSON data value. I'm using get method for reaching and server returns the JSON with 200 but when I try to reach JSON value it gives error.
My JSON:
{
"user": [
{
"id": 2,
"userName": "Mehmet",
"email": "personal#test.com",
"sys_role": 3,
"tckn": "00000000000",
"fk_parkID": 81
}
],
"parks": [
{
"parkID": 1,
"parkName": "Park Name",
"latitude": 42,
"longitude": 29,
"fk_regionID": 2
}, // 107 more parks like the up one.
]
}
I've tried this for reaching "userName" value from "user".
var selectedUserInfo;
var parksInfo;
selectUser(id) async { // This is selecting a person for doing some process on his/her account.
var result = CallApi().getData('admin/user/${id}', _setHeaders());
selectedUserInfo = jsonDecode(result.body)["user"][0]["userName"];
parksInfo = jsonDecode(result.body)["parks"];
setState(() {
});
}
When I
print(selectedUserInfo)
it returns null.
Your getData() method is probably an asynchronous method (Future).
If you don't wait for it, the result will be null, so the selectedUserInfo.
You should add the await keyword like this :
var result = await CallApi().getData('admin/user/${id}', _setHeaders());
I hope that will solve your issue
Related
I am practicing pulling data from an API using React and can't seem to figure out how to pull more than just one page of data.
"info": {
"count": 493,
"pages": 25,
"next": "https://rickandmortyapi.com/api/character/?page=2",
"prev": ""
},
"results": [
{
"id": 1,
"name": "Rick Sanchez",
"status": "Alive",
"species": "Human",
"type": "",
"gender": "Male",
},
{
"id": 2,
"name": "Morty Smith",
"status": "Alive",
"species": "Human",
"type": "",
"gender": "Male",
That is how the JSON data is structured and there are 20 people per page. I'm thinking it has something to do with using .com/API/character/next path somehow but can't wrap my head around it due to inexperience. This is my call in the App.js file.
function App() {
const [characters, setCharacters] = useState([]);
useEffect(() => {
async function fetchChar() {
let res = await fetch("https://rickandmortyapi.com/api/character/")
let data = await res.json();
setCharacters(data.results);
}
fetchChar();
}, [])
This is how I return like this in my Characters.js component file (Using semantic-UI-react). This has the first 20 characters show up on the page.
return(
<div>
<h1>People</h1>
<Grid columns={4}>
{data.map((characters, i) => {
return (
<Grid.Column key={i}>
<Card>
<Card.Content>
<Card.Header>{characters.name}</Card.Header>
<Card.Description>
<strong>Status</strong>
<p>{characters.status}</p>
I feel like there should be an easier way to pull from multiple pages, but after about 3 hours of research I still can't figure it out.
Is there a way to pull all 493 characters from all 25 pages or will I have to make 25 different fetch calls?
You're getting paginated results from the API. Either you need to use an API call that returns the entire data set (if it exists), OR you need to make 25 calls. You would just keep fetching with the value of next, adding to the array of data you're collecting until next presumably is empty and the calls would stop.
do a Promise.all on the rest of the pages
async function fetchChar() {
let res = await fetch("https://rickandmortyapi.com/api/character/");
let data = await res.json();
const restOfThepages = await Promise.all(
Array(data.info.pages - 1)
.fill(0)
.map(i =>
fetch(`https://rickandmortyapi.com/api/character/?page=${i + 2}`).then(res => res.json()).then(d => d.results)
)
);
const flattenedData = restOfThepages.reduce((acc, d) => [...acc, ...d], []);
return [...data.results, ...flattenedData];
}
I am building an autocomplete functionality.
1) The backend RESTful service returns following response for partially entered keyword.
JSON response
{
"suggest": {
"resultsuggest": [
{
"text": "Ke",
"offset": 0,
"length": 2,
"options": [
{
"text": "Kevin Johnson",
"_index": "customernames",
"_type": "_doc",
"_id": "1",
"_score": 3
}]
}
]
}
}
2) In Angular application, what should I do to extract the options array from the JSON response and return it back for this fetch function??
Note - I want to use the Promise instead of Observable.
fetch(params?: HttpParams): Promise<any> {
const query = params.get('query');
const headers = new HttpHeaders().set("Content-Type", "application/json");
let postData = "{ \"_source\": \"suggest\", \"suggest\": {\"resultsuggest\" : { \"prefix\" : \""+query+"\",\"completion\" : { \"field\" : \"suggest\", \"size\" : 5 }}}}";
return this._http.post<any[]>('http://127.0.0.1:9200/customernames/_search?pretty',postData, {headers})
.pipe(map(result=> {
// what should I do to extract the Options array from the JSON response and return it back in this fetch function??
return ????;
}),
delay(400)
).toPromise();
}
Appreciate your help!
thanks!
Updated:
1) JSON response is fixed.
2) changed return this._http.post<any> to return this._http.post<any[]>
As Arcteezy suggested, the following worked
map(result=> { return result.suggest.resultsuggest[0].options; }
I am getting JSON response like this. But I want to remove "headers", "original" and "exception".
{
"headers": {},
"original": [
{
"id": 271,
"name": "TestController",
"parent_id": null
}
],
"exception": null
}
Output expected:
{
"data": {
"id": 271,
"name": "TestController",
"parent_id": null
},
"errors": [],
"success": true,
"status_code": 200
}
You are returning a response()->json() inside another response()->json() something along the way:
response()->json(response()->json($data,200),200)
or more like:
$data = [
"id"=> 271,
"name"=> "TestController",
"parent_id"=> null
];
$response = response()->json($data,200);
return response()->json($response ,200);
You may not have notice it because of a function returning the first response()->json() into the second one
You can use this
$json='{
"headers": {},
"original": [
{
"id": 271,
"name": "TestController",
"parent_id": null
}
],
"exception": null
}';
$arr=json_decode($json);
$data=$arr->original[0];
$new_json=array();
$new_json['data']=$data;
$new_json['errors']=[];
$new_json['success']=true;
$new_json['status_code']=200;
$new_json=json_encode($new_json);
You may have doubled the data json return with response()->json()
you can use array only
return ["data"=> [
"id"=> 271,
"name"=> "TestController",
"parent_id"=> null
],
"errors"=> [],
"success"=> true,
"status_code"=> 200
];
In my case this problem solved with this solution:
You can use:
return json_decode(json_encode($ResponseData), true);
And return response
This is what I did, and it worked for me:
just call the original object after getting your response like this:
public function user_object(){
return $this->me()->original;
}
This is the me() function that returns user details
public function me()
{
return response()->json(auth('users')->user()->only(['id','name','email','status','phonenumber','type']));
}
This is my response from post man:
{
"success": true,
"user": {
"id": 29,
"name": "test6",
"email": "test6#gmail.com",
"status": 1,
"phonenumber": "413678675",
"type": "user"
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9hdXRoXC9yZWdpc3RlciIsImlhdCI6MTU5OTQ3MDc3OCwiZXhwIjoxNTk5NDc0Mzc4LCJuYmYiOjE1OTk0NzA3NzgsImp0aSI6InFyUWEyTVNLVzR4a2o0ZVgiLCJzdWIiOjI5LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.SMHgYkz4B4BSn-fvUqJGfsgqHc_r0kMDqK1-y9-wLZI",
"expires_in": 3600
}
The issue is triggered because you are returning nested responses somewhere in your code.
Here is a simple code that demonstrates the issue and the fix.
// A normal function that you think it returns an array
// but instead, it is returning a response object!
public function get_data(){
//ISSUE
return response([1, 2, 3]); // <- this will trigger the issue becuase
// it returns the data as a response not an array
//FIX
return [1, 2, 3]; // <- this will work as intended
// bacause the data is returned as a normal array
}
public function get_all_data(){
$first_array = [1, 2];
$second_array = [2, 3];
$third_array = get_data(); // <- here is the call to the function
// that should return an array
//Return the JSON response
return response([first_array, second_array, third_array]);
}
Was trying to extract values from a parsed json object using a function node or split & switch node, tried to many ways and nothing seems to work fro me.
the example below I would like to have 5 outputs for the text and numeric values.
here is my payload in json:
{
"applicationID": "1",
"applicationName": "test_ds18b20",
"deviceName": "arduino_uno",
"devEUI": "1234567890123456",
"rxInfo": [
{
"mac": "aa755a0048050130",
"rssi": -57,
"loRaSNR": 10,
"name": "raspberry_pi",
"latitude": 1.466860686785175,
"longitude": 2.019478797912605,
"altitude": 0
}
],
"txInfo": {
"frequency": 868100000,
"dataRate": {
"modulation": "LORA",
"bandwidth": 125,
"spreadFactor": 7
},
"adr": true,
"codeRate": "4/5"
},
"fCnt": 9,
"fPort": 1,
"data": "Z29vZGJ5ZQ==",
"object": {}
}
first i try with function node to extract "data", but it returns array like this:
0: ""data":"Z29vZGJ5ZQ==""
1: "Z29vZGJ5ZQ=="
i dont need array i need string
function:
var regexsearch = /\"data\":\"(.*?)\"/i;
var my = msg.payload.match(regexsearch);
msg.payload = my;
return msg;
but i need to get only this Z29vZGJ5ZQ==
than i try with split & switch nodes and gets the whole linelike this: ""data":"Z29vZGJ5ZQ==""
but i need to get only this Z29vZGJ5ZQ==
and here is my flow:
[{"id":"d46d38e2.27cc78","type":"inject","z":"ff592a31.cf21a8","name":"","topic":"","payload":"{\"applicationID\":\"1\",\"applicationName\":\"test_ds18b20\",\"deviceName\":\"arduino_uno\",\"devEUI\":\"1234567890123456\",\"rxInfo\":[{\"mac\":\"aa755a0048050130\",\"rssi\":-57,\"loRaSNR\":10,\"name\":\"raspberry_pi\",\"latitude\":48.466860686785175,\"longitude\":35.019478797912605,\"altitude\":0}],\"txInfo\":{\"frequency\":868100000,\"dataRate\":{\"modulation\":\"LORA\",\"bandwidth\":125,\"spreadFactor\":7},\"adr\":true,\"codeRate\":\"4/5\"},\"fCnt\":9,\"fPort\":1,\"data\":\"Z29vZGJ5ZQ==\",\"object\":{}}","payloadType":"json","repeat":"","crontab":"","once":false,"x":90,"y":160,"wires":[["1a34819e.743eee"]]},{"id":"105db6d9.0df1c9","type":"debug","z":"ff592a31.cf21a8","name":"","active":true,"console":"false","complete":"false","x":610,"y":100,"wires":[]},{"id":"1ac8a3e1.8f379c","type":"split","z":"ff592a31.cf21a8","name":"","splt":",","spltType":"str","arraySplt":"1","arraySpltType":"len","stream":false,"addname":"","x":250,"y":340,"wires":[["c10ec515.102d38"]]},{"id":"c10ec515.102d38","type":"switch","z":"ff592a31.cf21a8","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"\"data\":","vt":"str"},{"t":"cont","v":"\"latitude\":","vt":"str"}],"checkall":"true","outputs":2,"x":370,"y":340,"wires":[["105db6d9.0df1c9"],["6b2d5d19.7868e4"]]},{"id":"1a34819e.743eee","type":"json","z":"ff592a31.cf21a8","name":"","pretty":false,"x":115.55555555555556,"y":312.22222222222223,"wires":[["1ac8a3e1.8f379c","bae9fa5d.a9f238"]]},{"id":"bae9fa5d.a9f238","type":"function","z":"ff592a31.cf21a8","name":"match","func":"var regexsearch = /\\\"data\\\":\\\"(.*?)\\\"/i;\nvar my = msg.payload.match(regexsearch);\nmsg.payload = my;\nreturn msg;","outputs":1,"noerr":0,"x":310,"y":160,"wires":[["105db6d9.0df1c9"]]},{"id":"6b2d5d19.7868e4","type":"debug","z":"ff592a31.cf21a8","name":"","active":true,"console":"false","complete":"false","x":610,"y":180,"wires":[]}]
Thanks for help
I want to update an existing object/image in a Google Slide. This works as long as the object exists:
var requests = [
{
"deleteObject": {
"objectId": 'image01'
}
},
{
"createImage": {
"url": imageUrl,
"objectId": 'image01',
"elementProperties": {
"pageObjectId": pageId,
"size": {
"width": {
"magnitude": 250,
"unit": "PT"
},
"height": {
"magnitude": 250,
"unit": "PT"
}
},
"transform": {
"scaleX": 1,
"scaleY": 1,
"translateX": 200,
"translateY": 100,
"unit": "PT"
}
}
}
}
];
var response = Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
However, if a user previously deleted the object in the presentation, it is not re-created.
The following error message appear:
Invalid requests[0].deleteObject: The object (image01) could not be
found.
How can I query whether an object exists in presentation?
How about retrieving a object list using slides.presentations.get? In order to confirm whether objects exist, it uses slides/pageElements/objectId for fields of slides.presentations.get. You can know the exist of objects using the object list.
Sample script :
var response = Slides.Presentations.get(presentationId);
response.slides.forEach(function(e1, i1){
e1.pageElements.forEach(function(e2){
Logger.log("Page %s, objectId %s", i1 + 1, e2.objectId);
});
});
Result :
Page 1.0, objectId ###
Page 2.0, objectId ###
Page 3.0, objectId ###
If this was not useful for you, I'm sorry.
Edit :
If you want to search a value from whole JSON, you can use following simple script. When value2 is included in sampledata, ~JSON.stringify(sampledata).indexOf('value2') becomes true. In this sample, ok is shown, because value2 is included in sampledata.
But it's a bit of a stretch. If you can know the complete structure of JSON, I think that the compare of value using key is better.
var sampledata = {key1: "value1", key2: "value2"};
if (~JSON.stringify(sampledata).indexOf('value2')) {
Logger.log("ok")
}