I want to show some data from JSON string by making that string to array
I have used json_decode to convert the json string into an array. Here is my json string (dd):
"{"title":"W3Schools Online Web Tutorials","description":"w3schools.com","image":"http:\/\/www.w3schools.com\/images\/colorpicker.png","url":"https:\/\/www.w3schools.com\/"}"
When I am returning the array or dd the array, that showing me the array as I intended (dd):
array:4 [▼"title" => "W3Schools Online Web Tutorials""description" => "w3schools.com""image" => "http://www.w3schools.com/images/colorpicker.png""url" => "https://www.w3schools.com/"]
But then when I am trying to show $myarray->title it is giving me error:
Trying to get property 'title' of non-object
public function showDetail(Request $request){
$rUrl = "http://api.linkpreview.net/?key=5c59318d927ca5c5b481c89a6c18a0a2623a61d568502&q=".$request->body;
$json_string= file_get_contents($rUrl);
$data= json_decode($json_string,true);
return view('showIn')->with('data', $data);
}
Expected result: W3Schools Online Web Tutorials
Actual result: Error:Trying to get property 'title' of non-object
Your JSON string is in double quotes for one, use single quotes.
Secondly, $myarray->title is what you would do if you were working with an object. Since your working with an array, do it like $myarray['title']
This will work.
$myjson = '{"title": "W3Schools Online Web Tutorials", "description":"w3schools.com","image":"http:\/\/www.w3schools.com\/images\/colorpicker.png","url":"https:\/\/www.w3schools.com\/"}';
$myarray = json_decode($myjson, true);
echo $myarray['title'];
It is an array so you should be able to access it like this $data['title'];
You should use response json instead of return view('showIn')->with('data', $data);
return response()->json($data);
but if you want to print json in your view you can simply do
$rUrl = "http://api.linkpreview.net/?key=5c59318d927ca5c5b481c89a6c18a0a2623a61d568502&q=".$request->body;
$json_string= file_get_contents($rUrl);
return view('showIn')->with('json', $json_string);
In your blade template use
{{ $json }}
Related
I am working with following APIs:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
https://store.steampowered.com/api/appdetails?appids=GAMEID
(gameid example: "730" - counter strike)
My goal with both of these is to search them for data. For example I want the first API to give me a name of a game based on it's ID and the second one to give me specific information about a game for example if it has trading cards (id:29 in the API).
I tried a few things but I am kinda lost on this beacuse I don't really understand JSON so I would really appreciate some help.
I am open to both PHP and JS solutions.
IN PHP, you can use the json_decode() function to convert JSON data into an array. You can them access the values as you do for a classic array :
$appID = 730 ;
$url = 'https://store.steampowered.com/api/appdetails?appids=' . $appID ;
$content = file_get_contents($url) ; // retrieve the JSON data string from the website
$data = json_decode($content, true); // convert the JSON string into PHP array
echo $data[$appID]['data']['name'] ; // Counter-Strike: Global Offensive
var_dump($data[$appID]['data']['is_free']); // bool(true)
I have this JSON encoded with PHP:
{
"id": "37",
"user_id": "1",
"account": "ssdv",
"amount": "5002",
"subject": "\u0647\u062f\u06cc\u0647",
"tags": "[{\"ttt\"}]"
}
the php array for above json was:
array (
'id' => '37',
'user_id' => '1',
'account' => 'ssdv',
'amount' => '5002',
'subject' => 'هدیه',
'tags' => '["ttt"]',
)
tags index is read from MySQL table with JSON datatype, so I can't change format of tags it have to be json array.
I've tried to decode first string as json by this code:
<script>
var obj = JSON.parse('{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":"[{"ttt"}]"}');
</script>
but it throws this error:
Uncaught SyntaxError: Unexpected token t in JSON at position 86 at JSON.parse (<anonymous>)
how can i parse this json as a valid json in javascript?
update
my table is like this:
id user_id account amount subject tags
37 1 ssdv 5002 هدیه ["ttt"]
tags field is MySQL json type.
I fetch this record and try to json_encode it, the tags index turns to "tags":"[{"ttt"}]" after encode. but it cause error when i try to JSON.parse(myEncodedRecord). it looks the tags have to be like this "tags":["ttt"]. I know I can achieve this by preg_replace() , but is there any better way?
JSON.parse('{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":["ttt"]}');
If tags are array why you need {}. I removed them and I was able to parse.
This worked for me in the console. It is safe to use parsing inside a try
if tags is a single entity like if we have 3 tags and we need to show only it's name we can simply put it as an array. only if we need to display multiple attributes we need to fetch it as an array of objects.
in first situation it will be like
"tags":["tag1name", "tag2name","tag3name"]
if it has multiple attributes
"tags":[{"name":"tag1name","type":"type1"},{"name":"tag2name","type":"type2"},{"name":"tag3name","type":"type3"}]
You can validate your JSON syntax with the help of the below website
https://jsonformatter.curiousconcept.com/
You have 2 issues in your JSON String:
1.) You cannot use array as a string. So please change the string "[{"ttt"}]" to [{"ttt"}].
2.) When you are initializing an object, you cannot specify an index alone. You should also specify the value. So in the above point notice the object initialization in the array. If you provide only one string it will consider that as the index not the value. This is javascript not PHP.
So you can either:
1.) Change the `[{"ttt"}]` to `[{"ttt":"test"}]`. That should work or
2.) Change the `[{"ttt"}]` to `[{"value":"ttt"}]` however you feel comfortable.
I have considered the first option so your result string is:
var txt = '{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":[{"ttt":"test"}]}'
Try this out and let me know if you face any issues.
Hope This Helps.
to avoid this error I had to decode tags field value first, then encode the whole array
code:
//get the record
$record = $this->db->get_where('table', ['id' => $id])->row_array();
//decode tags value
$record['tags'] = json_decode($expense['tags']);
//encode and use
$record = json_encode($record);
now it's a standard JSON.
I have an array of arrays in PHP that I need to send to javascript as JSON. The PHP script and AJAX call work, but the returned JSON string is not parse-able JSON; instead of an array of arrays, it just sticks the arrays together with no separators or container.
Example JSON String:
[{"id":"77","options":[],"price":"4.25","title":"Zeppoli's","spec":""}][{"id":"78","options":[],"price":"7.95","title":"Battered Mushrooms","spec":""}]
PHP Snippet that creates above JSON String:
$cartArr = array(); // array of objects to be jsonified
foreach($products as $product){
unset($newItem);
$newItem = array(
"id" => $product['itemID'],
"options" => $theseOptions,
"price" => $product['price'],
"title" => $product['name'],
"spec" => $product["special"],
"cartid" => $product['ID']
);
array_push($cartArr,$newItem);
echo json_encode($cartArr);
}
An attempt to JSON.parse() the string will result in the following error, unless the string is manually corrected.
Uncaught SyntaxError: Unexpected token [
You're building json in a loop, which means you're outputting MULTIPLE independent json strings, which is illegal syntax. e.g. you're doing
[0,1,2][3,4,5]
which is two separate arrays jammed up against each other. It would have to be more like
[[0,1,2],[3,4,5]]
to be valid JSON. You encode to json LAST, after you've completely build your PHP data structure, not piecemeal in the middle of the construction process.
e.g.
foreach(...) {
$array[] = more data ...
}
echo json_encode($array);
I have an array stored in a mysql table, like this:
[3,5,6,7,8]
When I select it, encode it as JSON in PHP and then parse it into a javascript object, instead of it becoming an array, it just becomes a string "[3,5,6,7,8]". I know it's not possible to store it as an array in a single field, so.. what could I do so it will convert properly to an array instead of string?
My current code:
test = JSON.parse('[{"id":43,"incidence":"[0,3,6,7]"}]')
I could solve it removing the " on the string, but mysql returns it with the string, php encodes with the quotes and javascript parses with quotes. So basically, is there a way to remove it in this process?
The problem lies on how you are constructing your array prior turning it into JSON. Since you are retrieving these results from the database, I am assuming you are constructing a multidimensional array that may look something like this:
$results = array(
array(
"id" => 43,
"incidence" => "[0,3,6,7]"
)
);
Because incidence is a string, it is giving you those errors when using it in JS. To solve you need to turn that string into an array. Now, since you might have more than one result (being that these are database results) you need to iterate through the result array and turn that string into an array like this:
foreach ($results as &$row) { // <-- notice the & symbol (Passing by reference)
$no_brackets = trim($row["incidence"], '[]');//if you stored your array as comma delimited value, you would not need this.
$row["incidence"] = explode(',', $no_brackets);
}
Lastly, use json_encode and pass it to JS.
Final Result:
<?php
foreach ($results as &$row) {
$no_brackets = trim($row["incidence"], '[]');
$row["incidence"] = explode(',', $no_brackets);
}
$json = json_encode($results);
?>
<script>
var obj = JSON.parse('<?= $json ?>');
console.log(obj);
</script>
Hope this helps.
You need to do a little fiddling to get this to work.
Try this
<?php
$string = '[3,5,6,7,8]';
$t = str_replace(array('[',']'), '', $string);
$array = explode(',', $t);
echo json_encode($array);
The result is
["3","5","6","7","8"]
I have a simple code that switches two values in DB and returns them back to jQuery, so I can switch them for user without need to refresh a apge.
The thing is, I return it as array, console.log shows array ok, but I have no idea how to get the data from array.
Return by PHP:
$data = array($id, $img1, $img2);
echo json_encode($data);
jQuery:
$.post("bg_images_ajax.php", "switch=yes&id="+id).done(function(data){
$("#image-left-"+id).attr("src", "/images/backgrounds/"+data[1]).attr("alt", data[1]);
$("#image-right-"+id).attr("src", "/images/backgrounds/"+data[2]).attr("alt", data[2]);
console.log(data);
});
The data[1] worked almost every time I was working with Ajax, but here it looks like it takes the whole returned array as a simple string (data[2] returns 6 which is third character in the array ["6", "blabla", "blalablala"] returned by console.log).
I tried to have the array be returned as:
["id" = "6", "img1" = "blabla", "img2" = "blalablala"]
And to use this to get what I needed:
data.img1
But this just returns undefined.
I checked the page about jQuery.post http://api.jquery.com/jquery.post/
But I am either blind or just too tired, as I do not see what am I doing wrong.
Ps.: I also tried putting format of response to jQuery code, but it did not work (as I am not really sure where exactly to place it, tried two places, as shown here (not simultaneously)).
$.post("bg_images_ajax.php", "switch=yes&id="+id, "json").done(function(data){
$("#image-left-"+id).attr("src", "/images/backgrounds/"+data[1]).attr("alt", data[1]);
$("#image-right-"+id).attr("src", "/images/backgrounds/"+data[2]).attr("alt", data[2]);
console.log(data);
}, "json");
The PHP is missing
header("Content-Type: application/json");
and defaulting to sending text/html.
jQuery treats the result as a string of (invalid) HTML instead of parsing the JSON into the expected data structure.
Additionally, if you want an object (with named properties) instead of an array (which is accessed by numerical index), then you have to start with an associative array in PHP:
$data = array("id" => $id, "img1" => $img1, "img2" => $img2);