I have some html code, which also includes a javascript tag and some json inside.
The json object looks like this:
var data = {"service_notice":"111111-aa-bb-222222"}
I would like to extract the value for service_notice. How can this be done with regex?
I am also concerned that it could be formatted slightly differently:
var data = {"service_notice" : "111111-aa-bb-222222"}
or
var data = {
"service_notice" :
"111111-aa-bb-222222" }
You can use json_decode
json_decode(substr($code, strpos($code, "{")-1, strpos($code, "}") - strpos($code, "{") + 2), true)
will yield an array that looks like
array("service_notice"=>"111111-aa-bb-222222");
Thanks #HamZaDzCyberDeV
Related
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
I am trying to pass an array to the browser using php and jquery but I the when I try to use the 'data' returned from php's encode_json, it comes up undefined. I'm just learning php, jquery, and json and so far haven't found very good documentation on alot of this stuff, especially json, even in the books I have. Thanks in advance!
Here is a stripped down version of the jquery I have
$(document).ready(function(){
var jsonResult;//I will want to be able to use the data in other functions
$.getJSON("json.php", function(data){
jsonResult = data;
var str;
var nuts = [203,204,205,207];
str = '<p>' + data[nuts[0]].NutraDesc + '</p>';
$('#stuff').html(str);
}
);
});
This is the php:
include_once 'databasePHP.php';
$json_tst = $db->query( "SELECT def.Nutr_No, NutrDesc, Nutr_Val, Units
FROM nutr_def as def JOIN nut_data as data ON def.Nutr_No = data.Nutr_No
WHERE data.NDB_No = 1001 LIMIT 0, 2");
$food = array();
while($row = $json_tst->fetch(PDO::FETCH_ASSOC))
{
$Nutr_No = $row['Nutr_No'];
$food[$Nutr_No][] = array(
'NutrDesc' => $row['NutrDesc'],
'Nutr_Val' => $row['Nutr_Val'],
'Units' => $row['Units']
);
};
echo json_encode($food);
?>
which returns this json which I checked on jsonlint.com and it said it was valid:
{"203":[{"NutrDesc":"Protein","Nutr_Val":"0.85","Units":"g"}],"204":[{"NutrDesc":"Total lipid (fat)","Nutr_Val":"81.11","Units":"g"}]}
It probably doesn't work because the numbers should be strings. Try to add quotes around the numbers in nuts, like this:
var nuts = ["203","204","205","207"];
The following probably works as well:
str = '<p>' + data[String(nuts[0])].NutraDesc + '</p>';
Also, have you tried adding console.log(data); to the getJSON function to make sure it receives the JSON?
EDIT:
Here is a working JSFiddle from your code:
http://jsfiddle.net/rKLqM/
Things that were wrong:
you weren't parsing the result as JSON (JSON.parse)
NutraDesc was spelled wrong
You didn't convert the numbers to strings
You needed to add [0] to the jsonResult because there's an extra array within it (see the [])
In Javascript object property can be accessed with obj["propName"]
So, change
var nuts = [203,204,205,207];
to
var nuts = ["203","204","205","207"];
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);
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'];
First off, I do not want what is in the URL query. I want what PHP see's in the$_GET array.
This is because the URL query will not show all the params if mod_rewrite has been used to make pretty URLs
So is there a way to get the query string that would match exactly what is in the php $_GET array?
--
I came up with a way myself using PHP and JavaScript like so:
function query_string()
{
<?php
function assoc_array_to_string ($arr)
{
$a = array();
foreach($arr as $key => $value)
{
$str = $key.'='.$value;
$a[] = $str;
}
return implode("&",$a);
}
?>
return '<?=urlencode(assoc_array_to_string($_GET))?>';
}
...but I need to do this with just javascript if possible because I can't put PHP code in a .js file.
Won't JavaScript "only see" the query string? How would client-side script know about any rewrite rules?
The only way I can think of is to use PHP -- echo it into a variable in an inline script in your main page rather than the JS file.
In your page <head>:
<script type="text/javascript">
var phpQueryParams = <?php print json_encode($_GET); ?>
</script>
Assuming at least PHP 5.2, otherwise use an external package
The query string is found in window.location.search, but that's the raw query string. So if you run something like this:
(function () {
QueryStr = {}
QueryStr.raw = window.location.search.substr(1);
var pairStrs = QueryStr.raw.split('&');
QueryStr.val = {}
for(var i=0,z=pairStrs.length; i < z; i++) {
var pair = pairStrs[i].split('=');
QueryStr.val[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
})();
You'd have something very much like $_GET in QueryStr.val.
Of course, you mention that you've mixed things up a bit using mod_rewrite, which is cool, but since we don't know your rewrite scheme, we can't help specifically with that.
However... you know your rewrite scheme, and you could probably modify the code I gave above to operate on some other part of window.location. My bet is that you'd want to split window.location.pathname on the / character instead of &.