Parsing a JSON array of arrays using PHP [duplicate] - php

This question already has answers here:
how to parse json into php
(5 answers)
Closed 8 years ago.
I know this is rather simple but I'm stuck at it and I'd really like some help
Here's a JSON string I'm generating.
[{"field1":3,"field2":"5","field3":"value3","field4":"value4"},{"field1":3,"field2":"8","field3":"value3","field4":"value4"},{"field1":3,"field2":"6","field3":"value3"}]
How do I extract the value associated with field1?
And how do I access elements of each of the distinct arrays?

try this code
$jsonString = '[{"field1":3,"field2":"5","field3":"value3","field4":"value4"},{"field1":3,"field2":"8","field3":"value3","field4":"value4"},{"field1":3,"field2":"6","field3":"value3"}]';
$json = json_decode($jsonString, true);
print_r($json);

Try this (in Javascript)
var jsonData=[{"field1":3,"field2":"5","field3":"value3","field4":"value4"},{"field1":3,"field2":"8","field3":"value3","field4":"value4"},{"field1":3,"field2":"6","field3":"value3"}];
if you get response as text then use jsonData=JSON.parse(yourResponseText);
for(var i=0;i<jsonData.length;i++){
alert('your required val:'+jsonData[i].field1);
}
In php
$data = json_decode($json);//$json is your json data
foreach ($data as $item) {
echo $item->field1
}

https://stackoverflow.com/a/3627901/485790
console.log(jQuery.parseJSON(' [{"field1":3,"field2":"5","field3":"value3","field4":"value4"},{"field1":3,"field2":"8","field3":"value3","field4":"value4"},{"field1":3,"field2":"6","field3":"value3"}]').field1);

In php way
$jsonString = '[{"field1":3,"field2":"5","field3":"value3","field4":"value4"},{"field1":3,"field2":"8","field3":"value3","field4":"value4"},{"field1":3,"field2":"6","field3":"value3"}]';
$json = json_decode($jsonString, true);
foreach($json as $item){
echo $item['field1'];
}

In php you can:
$json = json_decode($_GET['variable'];
http://php.net/manual/en/function.json-decode.php

try this,
var json = '[{"field1":3,"field2":"5","field3":"value3","field4":"value4"},{"field1":3,"field2":"8","field3":"value3","field4":"value4"},{"field1":3,"field2":"6","field3":"value3"}]';
$.each(jQuery.parseJSON(json), function () {
alert(this['field1']);
alert(this['field2']);
alert(this['field3']);
alert(this['field4']);
});

this is a simple array of json objects. so with jquery
var jsonArray = JSON.parse("your string");
for(var int i=0 ; i < jsonArray.length() ; i++){
var jsonObject = jsonArray[i];
Console.log(jsonObject.field1)
}

Related

Convert from one json format to another [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a JSON formatted string that i get from an API call. however the format of the JSON string that i get from the API call is something similar to this.
{"offset":1,"result":{"host":"x.x.x.x","count":123"}}
I want it to be in the following format
{"offset":1,"result":[{"host":"x.x.x.x","count":123"}]}
Note: kindly look at the addition square braces in the folded JSON.
How can i achieve this in PHP . Im fairly new to PHP a little help here is appreciated. Thanks :)
You should be able to do this using PHP's json_decode() and json_encode() functions. Something like:
$jsonFromApi = '{"offset":1,"result":{"host":"x.x.x.x","count":123}}';
$array = json_decode($jsonFromApi, true);
$array['result'] = array($array['result']);
$newJson = json_encode($array);
Edit: Here is an example of using foreach for doing this to a series of comma separated json strings.
$originalData = '{"offset":1,"result":{"host":"x.x.x.x","count":123}},{"offset":2,"result":{"host":"x.x.x.x","count":123}},{"offset":3,"result":{"host":"x.x.x.x","count":123}}';
// Convert original data to valid JSON by wrapping it in brackets []. Makes it a JSON array.
$json = '['.$originalData.']';
$array = json_decode($json, true);
$convertedJsonStrings = array();
foreach ($array as $data) {
$data['result'] = array($data['result']);
$convertedJsonStrings[] = json_encode($data);
}
echo implode(',', $convertedJsonStrings);
Here we can't directly use json_decode() for $originalData since it is not valid JSON as it is.
Convert original into JSON object, take out result.
var originalJSONObj = JSON.parse(original);
var result = originalJSONObj.result;
Create another object with modifiedJSONObj.offset = 1 and modifiedJSONObj.result = [] and finally modifiedJSONObj.result.push(result).
In PHP, something like:
$json = '{"offset":1,"result":{"host":"x.x.x.x","count":123}}';
$data = json_decode($json);
$data->result = [$data->result];
$json = json_encode($data);
var_dump($json);
// i fixed the json that you are able to receive from the api
// maybe you could check it also
$data = '{
"offset": 1,
"result": {
"host": "x.x.x.x",
"count": "123"
}
}';
// decode the json from api
$data = json_decode($data, true);
// create new data from decoded data
$new_data = array(
'ofsset' => $data['offset'],
'result' => array(
$data['result']
)
);
// encode it again
echo json_encode($new_data);

Create a Javascript array from a PHP array

I am having trouble converting from a PHP array to a Javascript array and then accessing the value. I have tried JSON encoding and decoding.
PHP:
$simpleArray= [];
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null,$_product);
foreach($childProducts as $child) { //cycle through simple products to find applicable
$simpleArray[$child->getVendor()][$child->getColor()] = $child->getPrice();
var_dump ($simpleArray);
}
Javascript:
var simpleArray = <?=json_encode($simpleArray)?>;
//..lots of unrelated code
for(var i=0; i < IDs.length; i++)
{
console.log(simpleArray);
//which color id is selected
var colorSelected = $j("#attribute92 option:selected").val();
console.log('Value of color selected is ' + colorSelected);
$j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}
Edit:
I have gotten rid of the simpleArrayJson declaration in the php and changed the first line of the javascript.
The is no reason for you to json_decode() the value you are trying to output. Just echo it directly:
var simpleArray = <?= $simpleArrayJson ?>;
This will output a javascript object literal.
Remove from the php.
$simpleArrayJson=json_encode($simpleArray, JSON_FORCE_OBJECT);
here you are converting the php array into a json string.
Change in the javascript
var simpleArray = <?= json_encode($simpleArray, JSON_FORCE_OBJECT); ?>;
Here you are just outputting the sting. previously you where doing this
var simpleArray = <?=(array) json_decode($simpleArrayJson)?>
which after json_decode was returning an array, which you where casting to an array which then was cast to a string by the <?= so what ended up going to your browser was something like:
var simpleArray = Array;
try a for in loop.
for( item in data ) {
console.log(data[item]);
}
this is because json has keys that match the indexes of the array that was json_encoded, instead of necessarily 0->n indexes.
Edit thanks to comments changed data.item to data[item]

How to pass JS array via POST AJAX to PHP?

Here is my code:
var var_ids = new Array();
var i = 0;
jQuery("select").each(function() {
var_ids[i] = jQuery("option:selected",this).val();
i++;
}
var $data = {
action: "do_something",
var_ids: var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
And in my php:
$ids = mysql_real_escape_string(trim($_POST['var_ids']));
exit(print_r($ids));
And it just returns garbage...So my question is how to pass an array via AJAX to post php?
Thank you.
Most likely you get unexpected results because you apply string-related functions trim and mysql_real_escape_string to array $_POST['var_ids']
As long as it is just an array of integers - the only mysql sanitize you need is casting to int:
$ids = array_map('intval', $_POST['var_ids']);
print_r($ids);
$_POST['var_ids'] is an array in your example on the PHP side. You can only call trim and mysql_real_escape_string on strings not arrays. Try this in php:
$postData = isset($_POST['var_ids'])?$_POST['var_ids']):null;
if(is_array($postData)){
foreach($postData as $key=>$value){
$postData[$key] = mysql_real_escape_string(trim($value));
}
}
Viola, $postData is now a PHP array with trimmed and escaped values.
It's in the docs about 1/4 of a way down titled pass arrays of data to the server
var var_ids = new Array('10','12','13');
var $data = {
action: "do_something",
'var_ids[]': var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
Make it json_encoded array ... And then You can json_decode() the array properly.
You'll have better luck converting the array to a JSON object (Javascript Object Notation) and sending it that way.
Javascript JSON Instructions
JSON PHP Reference
You can either post each of the items with the key items[], then you could access the array as $_POST['items'] or you can serialize the array, send it and unserialize in PHP (JSON.stringify and PHP json_decode).

Parsing JSON in PHP

I´ve got the following JSON string:
{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}},"recipes_id":{"ranking_1":"9","ranking_2":"10","ranking_3":"7","ranking_4":"5"}},"Message":null,"Code":200}
How can I parse it in PHP and extract a list of TITLEs?
You can use the function json_decode to parse JSON data in PHP (>= 5.2.0, at least). Once you have a PHP object, it should be easy to iterate over all recipes/members and access their titles, using something like this:
$data = json_decode($json, true); // yields associative arrays instead of objects
foreach ($data['Data']['Recipes'] as $key => $recipe) {
echo $recipe['TITLE'];
}
(Sorry I can't actually run this code right now. Hope it helps anyway.)
If you want to do that in JavaScript, you can simply access JSON data like "normal" objects:
var jsonData = {
"Data": {"Recipes": {"Recipe_5": {"ID":"5","TITLE":"Spaghetti Bolognese"}}}
// more data
};
alert(jsonData.Data.Recipes.Recipe_5.TITLE);
This will print the TITLE of Recipe_5 in a message box.
EDIT:
If you want all the titles in a list, you can do something like this:
var titles = [];
for (var key in jsonData.Data.Recipes) {
var recipe = jsonData.Data.Recipes[key];
titles.push(recipe.TITLE);
}
alert(titles);

Read JSON Data Using PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 months ago.
Solr returns response in following JSON format.
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"indent":"on",
"start":"0",
"q":"*:*",
"wt":"json",
"version":"2.2",
"rows":"10"}},
"response":{"numFound":3,"start":0,"docs":[
{
"student_id":"AB1001",
"student_name":[
"John"]
},
{
"student_id":"AB1002",
"student_name":[
"Joe"]
},
{
"student_id":"AB1003",
"student_name":[
"Lorem"]
}]
}}
What will be the simple way to read student_id, student_name using PHP?
Use $obj = json_decode($yourJSONString); to convert it to an object.
Then use foreach($obj->response->docs as $doc) to iterate over the "docs".
You can then access the fields using $doc->student_id and $doc->student_name[0].
PHP has a json_decode function that will allow you to turn a JSON string into an array:
$array = json_decode($json_string, true);
$student_id = $array['response']['docs'][0]['student_id'];
...
Of course, you might want to iterate through the list of students instead of accessing index 0.
$result = json_decode($result, true);
$result['response']['docs'][0]['student_id'] ...
Why not just use one of the PHP clients for Solr, or the PHP response writer? See http://wiki.apache.org/solr/SolPHP
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
#array method
foreach($json_a['response']['docs'] as $students)
{
echo $students['student_id']." name is ".$students['student_name'][0];
echo "<br>";
}
#Object Method`enter code here`
foreach($json_o->response->docs as $sthudent_o)
{
echo $sthudent_o->student_id. " name is ".$sthudent_o->student_name[0];
echo "<br>";
}

Categories