I'm fairly new to json, and I'm having an issue with json_decode. I think I know why, but I haven't been able to sort out how to fix it.
Basically, I have a URL that supplies json info. I grab it using cURL, and return it as a PHP variable, and that's working just fine. I can print_r out all the info I want. However, when I use json_decode($json, true), it returns NULL.
I THINK it's because, technically, what's being returned is not a string, but more like an object - and I can't sort out how to grab the contents of that object.
For example, when I return the json stuff as a php variable:
print_r($json);
The output returned looks like so (I won't do it exactly, because it's HUGE, so I'll show you the layout to keep it simple)
MyThing.returnedItems({MyThing.returnedItems({
"projects":[{
"completed":"2010-12-21",
"status":"finished",
"favorited":0,
"started":"2010-12-20",
"percentage":78,
"permalink":"slug to post",
"size":"One size",
"thumbnail":{"src":"full path to full size image",
"medium":"full path to thumbnail"},
"name":"Some title here",
"notes":"description here",
"url":"URL to page",
"comments":0},
So you can see it's like a nested array. I don't mind that, but I'd like to be able to access all the key/value pairs of these arrays as PHP variables. But it seems because of the "MyThing.returnedItems()" surrounding it, it doesn't see it as a string to decode, so I get a NULL value every time.
Anyone know what I'm missing here? Once I figure out how to grab the stuff inside there, I think I've got it (simple foreach or whatnot to get the rest of the variables as needed), but I just can't seem to get in there.
This is valid JSON
{
"item1": [
{
"something": [],
"something else": "some value"
}
],
"another fun thing": [
{
"more fun": "fun value 1",
"even more!": "fun value 2"
}
],
"item2": {
"another thing": "another value"
}
}
This is not!
MyThing.returnedItems({
"item1":[{"something:[],
"something else": "some value"},
"another fun thing": [{"more fun": "fun value 1",
"even more!": "fun value 2"}]
],
"item2":{"another thing": "another value"}
})
Its a javascript method call
Okay, I just wanted to add that you all REALLY helped me out. Especially MaX, because by knowing the "official term" of what was happening, I had better searches and ended up finding some really interesting code that eventually landed me my solution. However, I did discover the reason why I was having my json wrapped in that weird function method call: the URL that the site gave me to access their API actually had that call in it, so it was returned wrapped in it. In other words, the json file URL I had was like so:
somesite.com/apicall.json?key=1234567890&callback=MyThing&version=0...
so as soon as I removed that "callback" section - BAM the json was no longer wrapped, and a whole new world of foreach functions opened up to me. So, even though the solution ended up being a REALLY stupid oversight on my part, I wanted to thank you all for your input, because I learned a whole lot of stuff I wasn't planning to today XD
Oh, and the code that actually ended up working (after I got rid of the callback part of the URL, because json_decode was still returning NULL on me) was this:
$data = json_decode(file_get_contents($json), true);
print_r($data); // array of everything available for me to mess with!
Thanks again for your help, everyone :) I REALLY appreciate it!
Related
I have a huge array of data in json format such as the shortened example below. And the only way to have the desired result was to encode and then decode, which seems quite absurd to me.
I can't find myself a better way to code this, i hope you can help me out
$exDummy= '[{"ID":"149467","date":"2018-03-23","name":"Bill", },
{{"ID":"149445","date":"2018-03-25","name":"Joe", },
{{"ID":"168841","date":"2018-04-05","name":"Lily", }]';
// This is how i actually solved it. But i dont think its the proper way.
$exDummy = json_decode($exDummy);
return JwtCheckHeader::json($exDummy);
So im basically asking if there is a direct way to return this without this workaround.
I've tried these solutions which should return json but none worked. I'm looking for something similar to the following
return JwtCheckHeader::json($exDummy);
echo json_encode($exDummy);
echo $exDummy;
return $exDummy;
(return type was set in the ajax call)
Edited for clarification
Im using CKEditor to store HTML input. Its working fine the one way. Data goes into the database exactly as I input it.
However, when I try to retrieve it in JSON, I get all sorts of parsing errors.
Here is a simple string which screws up
<p>This is my text</p>
<span style="font-size:14px">More test</span>
The JSON gets hung up on the double quotes, and the spaces. So I implemented this function in PHP before it gets inserted.
function parseline($string){
$string = str_replace(chr(10), "//n", $string);
$string = str_replace(chr(13), "//n", $string);
$string = str_replace(chr(34), "'", $string);
$string = str_replace("'","\'", $string);
return $string;
}
That line then becomes
<p>This is a test and more content</p>//n<span style=\'font-size:72px\'>
However. This still hangs up the JSON parsing.
How do I correctly store data from CKEditor, and then how to parse it back from the database, so that it can be parsed correctly as JSON??
Ideally I want to store it properly. And then I'll need to reverse parse the //n out to display back in the editor properly. Because right now, if I get valid data, I still get the //n displayed in the editor as actual values.
Ive been on this for 6 hours now. And Im tearing my hair out.
EDIT - Still stuck on this 22 hours later
Here is what is going into the database
<p>qweqweqweqwe</p>
And then Im getting it like this (using Lumen/laravel)
$post = Post::find($id);
return json_encode($post);
Then in Vue Im getting that json
el:'#app',
data : {
post: {}
},
methods: {
getPost: function(id){
var that = this;
$.ajax({
url:'post/'+id,
dataType:'json',
type:'GET'
}).done(function(data){
// Assign the data to Vue
that.post = JSON.parse(data);
}).fail(function(xhr){
});
}
}
This fails, with this exception
Uncaught SyntaxError: Unexpected token
in JSON at position 175
And the json returned is
{"uuid":"0bcb9c59-19da-4dcf-90d6-6dd53adfb449","title":"test","slug":"test","body":"<p>qweqweqweqwe</p>
","created_at":1519529598,"updated_at":1519534639}
So obviously its failing because there is an Enter key after the ending < /p >. But I already tried removing all enter keys and all that before storing. Replacing with new line /n. That works, but then I get //n back, and also things like style="font-size:14px;" from CKeditor, also make it fail, because of the double quotes.
So the issue is. Im storing the data exactly as its entered in the database. Retrieving it properly is just most definitely not working or easy to do at all it seems. At least as valid json.
EDIT 3 - Completeley lost and officially stumped
Im getting this back as json
var data = {
"uuid": "2cd2d954-233a-46d6-8111-29596262d3bc",
"body": "<p>test<\/p>\n",
"cover_img": "https:\/\/static.pexels.com\/photos\/170811\/pexels-photo-170811.jpeg",
"title": "asdf",
"slug": "asdf",
"created_at": 1519536364,
"updated_at": 1519538302
}
If i do
JSON.parse(data);
I consistently get
Uncaught SyntaxError: Unexpected token
in JSON at position 66
Even though if you copy that exact object over to JSONLint.com, its completely valid. Im so stumped. The most stumped I think I have ever been on any issue in my entire career. Which is wierd, because it seems like it would be such an easy bug to find.
Store it directly as HTML in the database. Don't modify, tweak, or otherwise screw with it at all - what's in the database should be exactly what the user submitted. (Stuff like XSS protection, parsing short codes, etc. should be done on display, so you can adjust your algorithms while still having the original HTML to work with.)
Provide it to Vue by running it through json_encode, which will escape it correctly:
$response = ['html' => $html];
return json_encode($response);
(You can also just do json_encode($html), which will return a JS-friendly string instead of a JSON object. Vue'll be happy with that, too.)
The resulting JSON will be:
{"html":"<p>This is my text<\/p>\n\n<span style=\"font-size:14px\">More test<\/span>"}
which Vue will be just fine with when you JSON.parse it.
Assuming a CKEditor instance named editor1, get CKEditor data, construct an object with it, stringify it and send it to database without PHP manipulation (JSON.stringify will take care of escaping characters):
JSON.stringify({'ckdata': editor1.getData()})
Retrieve data from database as text without PHP manipulation and parse it as JSON object:
JSON.parse(databasedata).ckdata;
EDIT: ceejayoz gave a better answer, since data is stored unmodified in database
I need to get brand: "hello world"
When I send using post data with json and get it with
$input = Input::all();
then with
die(print_r($input));
this is written
Array ([[], {brand: "hello world"}, [], 1427154586016])1
And
I tryed using json_encode and get with
die(print_r($encode));
this
{data: "{"brand":"Hello world"}", dc: "142715"}1
now if I do
$brand = $encode['data'] or $brand = $encode['brand']
I get an error.
How do I get Hello world to var $brand
It looks like you're using json_encode() when you should be using json_decode(). But like kamlesh pointed out, it appears that your original JSON data is not valid JSON to begin with, so this would not help you. This wiki article has an example of valid syntax.
Also, if you're using laravel, you can use the helper function dd(), which will die() and var_dump() automatically for you, saving you a bit of time.
Hopefully this solves your problem, but if not, read the docs for the Input. There should be something there to get you on the right track.
I have extracted data from another website which is in JSON format - here is what I extracted: http://sub7legends.net/crawler.php
I need to get the value of kills and deaths from this.
I tried json_decode() in php of this data but when I var_dump() the result it just says "NULL".
What can I do to extract the required data?
The link doesn't work for me. But if you have a normal json just like this one:
{"kills": "5", "deaths": "3"}
Then the json_decode() method should work.
Here would be a sample code snippet:
$json_you_got_from_the_server = '{"kills": "5", "deaths": "3"}';
$result = json_decode($json_you_got_from_the_server);
$kills = $result->kills;
$deaths = $result->deaths;
echo "You have ".$kills." kills and ".$deaths." deaths.";
I haven't tried it, but it should work. If it doesn't, then please comment and I will try something else.
the current json contents are not valid, try validating it first. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
That json in the link you have pasted has no proper ending scroll to the end and you will see. If this is the same thing that you wanted to parse then it will always return null.
Using PHP, I'm trying to grab data from the Goodreads API, which returns XML. I've been having a hell of a time trying to figure out how to pull data out of it.
At some point in the adventure, someone suggested I do a json decode( json encode ($blah)) of the whole thing and use JSON instead of XML.
That brings me to my current situation. Everything works as it should, up to the point where I'm pulling data out of the returned array. I probably should have spent more time reading and learning about arrays, but after more than two days of doing every Google search I could think of, I came here.
Here's the entirety of what gets returned by Goodreads:
a:2:{s:7:"Request";a:3:{s:14:"authentication";s:4:"true";s:3:"key";a:0:{}s:6:"method";a:0:{}}s:6:"search";a:7:{s:5:"query";a:0:{}s:13:"results-start";s:1:"1";s:11:"results-end";s:1:"1";s:13:"total-results";s:1:"1";s:6:"source";s:9:"Goodreads";s:18:"query-time-seconds";s:4:"0.06";s:7:"results";a:1:{s:4:"work";a:9:{s:11:"books_count";s:1:"7";s:2:"id";s:7:"5024045";s:24:"original_publication_day";s:2:"16";s:26:"original_publication_month";s:1:"9";s:25:"original_publication_year";s:4:"2008";s:13:"ratings_count";s:3:"227";s:18:"text_reviews_count";s:2:"53";s:14:"average_rating";s:4:"4.33";s:9:"best_book";a:5:{s:2:"id";s:7:"4958245";s:5:"title";s:37:"7 Habits of Happy Kids [With Earbuds]";s:6:"author";a:2:{s:2:"id";s:5:"38343";s:4:"name";s:10:"Sean Covey";}s:9:"image_url";s:56:"http://photo.goodreads.com/books/1343744353m/4958245.jpg";s:15:"small_image_url";s:56:"http://photo.goodreads.com/books/1343744353s/4958245.jpg";}}}}}
What I want from this array is the "id" variable appears under "best_book". For that, I'm using these lines of code:
$goodreads_results = json_decode(json_encode((array) simplexml_load_string($goodreads_data_a)), 1);
$goodreads_id = $goodreads_results->search->results->work->best_book->id;
I should point out that the array I posted (that began "a:2:{s:7") is what's contained in $goodreads_results after the above two lines of code. So I know everything UP TO that point works as it should.
For whatever reason, I'm not getting the ID. The $goodreads_id variable is empty.
Can somebody help me figure out why? Even though I know it's likely something basic, I'm lost, and everything is starting to look the same to me.
Try:
<?php
$goodreads_data_a = 'a:2:{s:7:"Request";a:3:{s:14:"authentication";s:4:"true";s:3:"key";a:0:{}s:6:"method";a:0:{}}s:6:"search";a:7:{s:5:"query";a:0:{}s:13:"results-start";s:1:"1";s:11:"results-end";s:1:"1";s:13:"total-results";s:1:"1";s:6:"source";s:9:"Goodreads";s:18:"query-time-seconds";s:4:"0.06";s:7:"results";a:1:{s:4:"work";a:9:{s:11:"books_count";s:1:"7";s:2:"id";s:7:"5024045";s:24:"original_publication_day";s:2:"16";s:26:"original_publication_month";s:1:"9";s:25:"original_publication_year";s:4:"2008";s:13:"ratings_count";s:3:"227";s:18:"text_reviews_count";s:2:"53";s:14:"average_rating";s:4:"4.33";s:9:"best_book";a:5:{s:2:"id";s:7:"4958245";s:5:"title";s:37:"7 Habits of Happy Kids [With Earbuds]";s:6:"author";a:2:{s:2:"id";s:5:"38343";s:4:"name";s:10:"Sean Covey";}s:9:"image_url";s:56:"http://photo.goodreads.com/books/1343744353m/4958245.jpg";s:15:"small_image_url";s:56:"http://photo.goodreads.com/books/1343744353s/4958245.jpg";}}}}}
';
$goodreads_results = unserialize($goodreads_data_a);
echo $goodreads_id = $goodreads_results['search']['results']['work']['best_book']['id'];
?>