Parsing JSON in PHP with a prepend of sorts - php

if my JSON data is coming back as this:
{"errorCodes":[0]}resultArray=[{....}]
how do I grab the resultArray as the actual JSON string and ignore the rest?
and why would I need errorCodes in front of it?

Just use string manipulation to get rid of everything up through resultArray= and then decode with json_decode().
$json_raw = '...'; // the raw "JSON" string
$delimiter = 'resultArray=';
$cleaned_json = substr($json_raw, strpos($json_raw,$delimiter) + strlen($delimiter)));
$object = json_decode($cleaned_json);

Related

request json located in a php file from c#

Could someone tell me how i request json from a php file located on another server that gives it to our asp.net?
It includes ~10 variables we want to use again.
I don't want just a string, but an array.
so this wont work:
//We don't actually use the given url of course
string url = "url";
var json = new WebClient().DownloadString(url);
Response.Write(json);
I'd like to use it somewhere like this jsonname[2]
Output a JSON array from your php page like this
$myArr = array("John", "Mary", "Peter", "Sally");
$myJSON = json_encode($myArr);
header('Content-Type: application/json');
echo $myJSON;
In your c# code you then need to deserialize the string returned by DownloadString into a type that matches the format of the JSON data. If your JSON is just an array of strings, then use JsonConvert.DeserializeObject<List<string>>(json) from the Newtonsoft.Json package. Otherwise you need to replace List with something that matches the Json data, for example a new class with all the same property names and types. In this case
string url = "url";
var json = new WebClient().DownloadString(url);
Response.Write(json);
var myArr = JsonConvert.DeserializeObject<List<string>>(json);
Response.Write(myArr[1]); // will output "Mary"
If you don't have Newtonsoft.Json, this question has some options for obtaining it

Json string conversion to json object

I have been stuck in this issue and cant seem to fix it.. I have this JSON STRING
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
I need to convert it into array of object or maybe just one json object.. I have tried doing
json_decode($unBilledArr , true);
It gives me null.
Already tried these solutions as well
Convert a string to JSON object php
https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
I must be doing something wrong.. cant seem to figure out what..
P.s : This is the response i am getting and i can not do anything about the response.
You are trying to decode an array, either specify the specific item within the array, or make it a string.
For instance:
$unBillableArr = '{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}';
$json = json_decode($unBillableArr, true);
// Or
$unBillableArr = ['{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}'];
$json = json_decode($unBillableArr[0], true);
However, given the string you are receiving does not contain valid JSON and you are unable to control what you receive, I have prepared the following that will replace the single quotes in your JSON, and decode each item into an array:
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
// Loop through each JSON string
$jsonObjects = []; // Change this name...
foreach ($unBillableArr as $jsonString) {
$jsonObjects[] = json_decode(str_replace("'", '"', $jsonString), true);
}
print_r($jsonObjects); // Proof it works
Please bear in mind that I would consider this to be a dirty fix. To fix this properly, you should go back to the source and ensure that the JSON they are returning to you is valid.

Remove String Before Json Response Body Php

Hi I am using WHMCS Api I am getting a response in json format like this
string 'userhowhigh83{"result":"success","orderid":787,"productids":"785","addonids":"","domainids":"","invoiceid":"766"}' (length=113)
I am getting the response correctly from API but it is also giving me the string 'userhowhigh83' where 'howhigh83' is the username and 'user' is given static but when I decode the json result it gives me null. I checked in on an online json decoder when I remove 'userhowhigh83' it will works fine.How can I remove this before json response body.
If you cannot get the string in better shape from your API, you always can use substring on your string to get rid of "userhowhigh83" :
$string = substr($string , strpos($string , "{"));
This will do as well:
list($username, $jsonData) = explode('{', $json);
echo '{' . $jsonData;
echo $username;
Another approach will be:
preg_match('/{.*?}/', $json, $matches);
echo $matches[0];

Extract Data from JSON URL

http://www.instamapper.com/api?action=getPositions&key=584014439054448247&num=10&format=json
is the url, which contains json data. I want to use that data and send SMS to a particular phone no if value of latitude and longitude(Extracted from JSON).
Check constraints, we can use through php. But the main problem is How to extract data from JSON file?
I don't want to give you the solution, so the below should be enough to get you started.
Read in the JSON data using file_get_contents
Parse the JSON string into a PHP object using json_decode
Your code should look something like this:
$url = "http://www.instamapper.com/api?action=getPositions&key=584014439054448247&num=10&format=json";
$contents = file_get_contents($url);
$jsonObj = json_decode($contents);
You mean something like this?
<?php
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo "{$trend->name}\n";
}

json inside function, (php parsing)

I have sth like that inside *.txt file.
function_name({"one": {"id": "id_for_one", "value": "value_for_one"}, ...});
And I am getting the file like this:
$source = 'FILE_NAME.txt';
$json = json_decode(file_get_contents($source),true);
echo $json['one']['value'];
It doesn't work, but when I remove function_name( and ); it works.
How to parse it without removing these strings?
You can't. It is not valid JSON with those. Take a substring that excludes them.
You will have to remove those strings. With the function_name portion it is not valid JSON.
A JSON string will typically either begin with { (object notation) or [ (array notation), but can also be scalar values such as a string or number. You cannot parse it without first making sure the string is valid JSON.
You are trying to get the string within a file and decoding it as a JSON file.
The 'function_name' isn't a valid JSON string, the rest inside yes.
How to parse it without removing these strings?
There is no way.
This should work for you.
$data = file_get_contents($source);
$data = substr($data, strlen("function_name("));
$data{strlen($data)-1}=$data{strlen($data)-2}=" ";
$json = json_decode($data,true);
Both {} and [] works for string to access individual characters.
The function in your text file, means that isn't a json file.
Remove the string using a regular expression, and your problem is fixed.
If the function is a fixed name, do something like this:
$source = 'FILE_NAME.txt';
$json_content = str_replace('function_name(', '', file_get_contents($source));
$json_content = substr($json_content,0,-2);
$json = json_decode($json_content,true);
echo $json['one']['value'];

Categories