How to access values in a multidimensional JSON array from backgrid template - json

I am trying to get json value from laravel json response to Backgrid template
My laravel json response is
return Response::json(
array(
'items'=> $articles->toArray()
));
It response json array like these
{"items":[{"id":30,"title":"Tester","body":"tesrter","user_id":566,"user_nickname_id":0,"category_id":1,"community_id":0,"ref_link":"face.com","status":3,"points":0,"editor_id":566,"created_at":"2015-03-21 15:53:43","updated_at":"2015-03-21 09:23:43","category":{"id":1,"name":"Cupcake wrappers","description":"","created_to":"2015-02-27 13:53:15","updated_to":"0000-00-00 00:00:00"}}]}
My backgrid cell is
var CateoryType = Backgrid.Cell.extend({
template: _.template('<%=category.name%>'),
render: function () {
this.$el.html(this.template( this.model.toJSON() ));
this.delegateEvents();
return this;
}});
But I couldn't get category 's name from json response.
How Could I get Category name from my Backgrid Cell or any other way to access it?

the problem being you are not returning an exact collection from your laravel, you can do it in either using backbone or laravel(optimal)
instead return just say
echo json_encode($articles->toArray());
Using backbone parse method:
in your collection use
parse : function(response){
return response.items
}

Related

typescript - load json from url and get access to array of json objects

I just can't find a working solution and implement in my format.
There is a JSON file which is returned to me by URL. Its format is:
{"success":true,
"data":[
{
"loadTimestamp":"2022-07-20T15:12:35.097Z",
"seqNum":"9480969",
"price":"45.7",
"quantity":"0.2",
"makerClientOrderId":"1658329838469",
"takerClientOrderId":"1658329934701"
},
{
"loadTimestamp":"2022-07-20T14:49:11.446Z",
"seqNum":"9480410",
"price":"46",
"quantity":"0.1",
"makerClientOrderId":"1658328403394",
"takerClientOrderId":"0"
}]
}
Due to the fact that it is returned via the URL, it is not possible to directly use the object, for example:
myobj['data']['price']
I have either a string of data that I can convert using JSON.parse() or an object right away.
But for some reason I can't use it directly.
As far as I understand, this is a JSON file inside which is an array of JSON data.
My goal is to display all the data from the array, while taking for example 2 values: price, quantity
How can I access the values that I want to get?
Ok I find, what I was looking for.
I return result not in json, but in text response.text()
After I did this, I create a new constant called res and put in it JSON.parse(data)
const url = 'https://myurl.com/'+pub_key
const response = await fetch(url)
let data = ''
if (response.ok) { data = await response.text() } else { console.log("Error HTTP: " + response.status) }
const res = JSON.parse(data)
After all this manipulations I can use my data with 2 ways:
console.log(res["data"][0]["price"])
console.log(res.data[0].price)
Or I can make a cocktail from it, by using my favorite blender :)))
if(res.success==true){
for(let item in res.data){
console.log(res.data[item].price,res.data[item].quantity)
}
}

Not able to get value from Json key

I am trying to get an object from Mongoose but when I get it and try to access the Json object by key to get the value i get undefined.
User.find({name: 'auth'},function (err,obj) {
var authCode = JSON.stringify(obj);
console.log(authCode);
var parse = JSON.parse(authCode);
console.log(parse);
console.log(parse.code);
});
I get the following output:
[{"_id":"5a43b491734d1d45eaf2d00d","name":"auth","code":"nCAxOSrUMqxtxd8T"}]
[ { _id: '5a43b491734d1d45eaf2d00d',
name: 'auth',
code: 'nCAxOSrUMqxtxd8T' } ]
undefined
I have even tried console.log(parse['code'])and i still get undefined. Can someone please help me
parse variable above is not a dictionary itself, but an array containing a dictionary. What you should do to access the code field would be first access the dictionary and then get the code field like;
parse[0].code
or
parse[0]['code']
You need not parse or stringify the returned JSON object. You can use the JSON object as it is. Try below approach
User.find({name: 'auth'},function (err,obj) {
console.log(obj);
console.log(obj.code);// this will probably be undefined as find method returns array of objects ( correct me if iam wrong)
user.forEach(function(obj,index){
console.log("index: "+index);
console.log("obj: "+obj.code);
});
});
Using promises is a good way
User.find({name: 'auth'})
.then((user)=>{
console.log("find success");
console.log(user);
console.log(user.code); // would return undefined as User.find will return array of objects
user.forEach(function(obj,index){
console.log("index: "+index);
console.log("obj: "+obj.code);
});
})
.catch(()=> {
console.log("find failed");
});

how to pass JSON data to view in laravel

I want to pass this JSON data to some view but don't know how its works.
I have used, make view also, and convert this data to JSON and pass other way but it didn't work
$items = Items::all();
return response()->JSON($items);
e.g view is items.create
For Laravel ver 4.2,
You can pass your data to your blade view with a variable (eg:$data) having an array which will be used in your blade.
$flag is variable being used in the JS part of your code, so you can pass that also as an array: Response::json(['param1' => $foo1, 'param2' =>$foo2)]);
In your controller return the view:
return Response::json(['view' => View::make('yourbladename', $data)->render(), 'flag'=>$flag]);
In your JS use the data variables as:
function(data){
$('#DivToAppendHTML').append(data.view); //this appends html blade to the Div having the ID DivToAppendHTML
if(data.flag == 1){ //this uses the second variable passed in controller for any other purpose
$('.classname').remove();
}
}
If you want to create JSON response, you need to convert collection to an array:
$items = Items::all()->toArray(); // $items is array now
return response()->json($items);
If you want to pass some JSON data to a view, do this:
$items = Items::all()->toJson();
return view('items.create', compact('items'));

zf2 How to save json return value to a variable

i have this code to return json
return new JsonModel(array(
'id' => $id,
'name' => 'ana',
));
that code will return this
{"id":"83493","name":"ana"}
my question is how do i save id value to a variable. lets just say my variable is $a. How do i save 83493 to $a?
I assume you are returning the json array from a controller's action to a view file.
Was this action called via some ajax call? If yes then, on success of that ajax call, you will have something as -
$.ajax({
.....
.....
.....
success: function(data) {
var a = data.id; //Here variable a will have value as 83493
},
});
As you are sending the array and not just a single value, the data parameter in the success function will act like a object and so id and name will become its properties.
Properties should be accessed via dot (.) operator Eg: data.id and data.name
I hope this is what you are expecting, please let us know if its not.

Convert JSON object to array?

I have this on my console on firebug,
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...}, Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
it is data from the server side. Now, how would I convert this into array such that this data can be used on another file. I tried JSON.parse and jQuery.parseJSON but both did not work.
That isn't JSON it's a Javascript array of objects, not a string. My guess is that you've received this from a jQuery ajax call and you had the dataType : 'json' set so that jQuery has automatically parsed the JSON into this array.
To send it to a PHP script you can convert it back to JSON using:
var myString = JSON.stringify(data);
and then fire off an ajax call to the PHP script with that as the POST data:
var myString = JSON.stringify(data);
$.post('page.php', { data : myString }, function(){
console.log( "sent" );
});
In PHP you can decode it using:
$data = json_decode($_POST['data']); // <-- or whatever your post variable is named
foreach($data as $obj)
{
echo $obj->fa_id;
}
if you want to get an php array use this
http://php.net/manual/en/function.json-decode.php
The string you provided is not valid JSON.
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...},
Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
In particular, the "Object" and "more..." strings cannot be interpreted by a JSON parser.
Assuming the object you are inspecting is a variable named foo:
console.log(JSON.stringify(foo));
Should print a valid JSON representation of your object to the Javascript console.