I have a quite nested JSON file. How can I delete an array that includes my value? For ex: I want to delete {"customer":"Customer1","date":"2017-06-03"...} from JSON file and I already knew the "Customer1"
{
"info": [{
"customer": "Customer1",
"date": "2017-06-03",
"beacons": [{
"data1": "1234",
"data2": "Test1",
}, {
"data1": "0088",
"data2": "Test2",
}]
},{
"customer": "Customer2",
"date": "2017-06-03",
"beacons": [{
"data1": "dcdd4",
"data2": "Test3",
}, {
"data1": "0088",
"data2": "Test4",
}]
}]
}
Thanks!
There is some issue in your json data. This is not valid json data; I have decoded the josn data & then check if "customer" value = 'Customer1', then remove the array from main array.
It should be like this:
$jsonData = '{"info ": [{
"customer ": "customer1 ",
"date ": "2017 - 06 - 03 ",
"beacons ": [{
"data1 ": "1234",
"data2 ": "Test1"
}]
}, {
"customer": "customer2 ",
"date": "2017 - 06 - 04 ",
"beacons": [{
"data1": "dcdd4",
"data2": "Test3"
}]
}]
}';
$myData = json_decode($jsonData,true);
foreach($myData["info"] as $k=>$arr) {
if($arr["customer"] == "customer1") {
unset($myData["info"][$k]);
}
}
one small correction in the previous answer .
please call function like this . the searching value should be a value like astring format .
searchObj (myobj, 'Customer1');
make the object to assign to one obj example :=>
var myobj={"info": [{ ...... }]}
.this below function will work for the searching the exact value in object array
call the function with the parameters as like below
searchObj (myobj, Customer1);
function searchObj (obj_name, searchingval) {
for (var key in obj_name) {
var value = obj_name[key];
if (typeof value === 'object') {
searchObj(value, searchingval);
}
if (value === searchingval) {
console.log('property name=' + key + ' property value=' + value);
}
}
}
Related
I am trying to get a json result to an array object .I am echoing a json data in php. like this.
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type:application/json;charset=utf-8');
$arr= '[{
"id": "1",
"date": "2020-03-21",
"status": "present",
"studentid": "1"
},
{
"id": "2",
"date": "2020-03-24",
"status": "present",
"studentid": "1"
},
{
"id": "3",
"date": "2020-03-25",
"status": "absent",
"studentid": "1"
},
{
"id": "4",
"date": "2020-03-26",
"status": "absent",
"studentid": "1"
}
]';
echo $arr;
?>
~
How to get absentees using angular in an array.
Angular part i tried didnt work
this.http.post("http://localhost/android/Api.php?apicall=getattendance", JSON.stringify(this.postData),options)
.subscribe( (data) => {
this.setUsersArray(data);
console.log(data + "URL DATA"+JSON.stringify(this.postData));
}
);
=====================================================================
setUsersArray(data){
if (data instanceof Array) {
{
this.date_present = data.map(function (ele) {
if(ele.status==='present')
{
return ele.date;
}
});
this.date_absent = data.map(function (ele) {
if(ele.status==='absent')
return ele.date;
});
}
}
I am getting date_absent and date_present as null.Why am i getting this as null.Please help me. I am new to angular.
try for loop in typescript
setUsersArray(data:any){
for(let item of data){
console.log(item);
if(item.status==='present') {
this.present.push(item.date);
}
if(item.status==='absent') {
this.absent.push(item.date);
}
}
Trying to this url
$characters = json_decode($data, true); // decode the JSON feed and make an associative array
https://www.taniarascia.com/how-to-use-json-data-with-php-or-javascript/
Im working with Google tag Manager API(v2), and trying to add some new lines to my existing JSON array. I first had some trouble adding data to my JSON object because the data was shown on the last row and not inside the object itself.
Now ive changed my code but the data does not look like its inside the object itself but im a little bit closer now. This is how my JSON object looks like now:
JSON:
{
"Account2": [{
"accountId": "17467*****",
"containerId": "745****",
}, 3, 3, 4, {
"accountId": "17467*****",
"containerId": "751****",
}, 1, 1, 2],
"Account 1": [{
"accountId": "17661*****",
"containerId": "748****",
}, 2, 1, 1],
"GTMdocx": [{
"accountId": "21200*****",
"containerId": "803****",
}, 0, 0, 1],
"Account3": [{
"accountId": "21281*****",
"containerId": "803****",
}, 0, 0, 0]
}
As you can see the object is structured like this:
1) Accountname
2) Inside Accountname we have accountId and containerId
3) at last of one Accountname object we have some numbers(count), the problem is that it looks like this:
What i would want the JSON-object to look like is like this:
{
"Account2": [{
"accountId": "17467*****",
"containerId": "745****",
"tags": "3",
"triggers": "3",
"variables": "4"
}, {
"accountId": "17467*****",
"containerId": "751****",
"tags": "3",
"triggers": "3",
"variables": "4"
}],
"Account 1": [{
"accountId": "17661*****",
"containerId": "748****",
"tags": "2",
"triggers": "1",
"variables": "1"
}],
"GTMdocx": [{
"accountId": "21200*****",
"containerId": "803****",
"tags": "0",
"triggers": "0",
"variables": "1"
}],
"Account3": [{
"accountId": "21281*****",
"containerId": "803****",
"tags": "0",
"triggers": "0",
"variables": "0"
}]
}
You can see the numbers got a key and then value inside the object.
This is my PHP-code:
static public function listAllContainers() {
try { //Because some containers might not have live-version
$containers[] = array();
foreach (self::listAccounts()->account as $accountKey => $account) {
foreach (self::listAccountsContainers($account["path"]) as $account_container) {
$containers[$account['name']][] = $account_container;
$container_version = self::listAccountsContainersVersion($account_container['path']);
$containers[$account['name']][] = count($container_version['tag']);
$containers[$account['name']][] = count($container_version['trigger']);
$containers[$account['name']][] = count($container_version['variable']);
}
}
$filtered_array = (object)array_filter((array)$containers); // Removes empty object
return $filtered_array;
} catch (\Exception $e) {
return $e->getCode();
}
}
Hope you understand my problem. Not so much experience with Arrays/JSON so maybe my explanation is not so good.
Thanks!
UPDATE:
Using $containers[$account['name']]['tag'] = count($container_version['tag']); gives me this JSON: (PS: ive removed some from the json so it wont be long, this makes the json invalid)
{
Account2: {
0: {
accountId: "174675****",
containerId: "745****",
},
1: {
accountId: "174675****59",
containerId: "751****83",
},
tag: 1,
trigger: 1,
variable: 2
},
Account 1: {
0: {
accountId: "1766***525",
containerId: "748***53",
},
tag: 2,
trigger: 1,
variable: 1
},
Now each "Account" can have multiple "containers"(accountId,containerId), using this method does not store the data inside the object itself.
If you have an array, you can add a key:value pair to it with the following syntax:
$array['key'] = 'value';
//array('key' : 'value')
If you don't specify a key, it will just add the value:
$array[] = 'value';
//array('value')
The last part is what you are doing now, but you add it to your $containers[...] array. What you want to do is add the values first to your $account_container array, and then add that array to your $containers[...] array. Put this in the inner foreach:
$container_version = self::listAccountsContainersVersion($account_container['path']);
//Add values to account_container
$account_container['tag'] = count($container_version['tag']);
$account_container['trigger'] = count($container_version['trigger']);
$account_container['variable'] = count($container_version['variable']);
// Add account_container to your $containers[..] array
$containers[$account['name']][] = $account_container;
I put together another solution without modifying the original $account_container.
I've added the new data in a new array $account_container_extra and merged that together with $account_container when appending it to the $container array.
Maybe that will work better for you or give you some other ideas.
static public function listAllContainers() {
try { //Because some containers might not have live-version
$containers[] = array();
foreach (self::listAccounts()->account as $accountKey => $account) {
foreach (self::listAccountsContainers($account["path"]) as $account_container) {
$container_version = self::listAccountsContainersVersion($account_container['path']);
$account_container_extra = [
'tag' => count($container_version['tag']),
'trigger' => count($container_version['trigger']),
'variable' => count($container_version['variable'])
];
$containers[$account['name']][] = array_merge($account_container, $account_container_extra);
}
}
$filtered_array = (object)array_filter((array)$containers); // Removes empty object
return $filtered_array;
} catch (\Exception $e) {
return $e->getCode();
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Please view my other question here
I am trying to work out how to decode a JSON response from a PHP file.
The JSON is structured as follows:
[{
"id": 1,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/amazon-webstore-379672",
"price": " - "
}
}, {
"id": 2,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671",
"price": "\u00a3 50 "
}
}, {
"id": 3,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670",
"price": "\u00a3 50 "
}
}, {
"id": 4,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/1-to-2-developers-to-work-on-a-large-project-379669",
"price": " - "
}
}, {
"id": 5,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/we-would-like-someone-to-design-some-world-cup-t-shirts-for-379665",
"price": "\u00a3 50 "
}
}, {
"id": 6,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/graphic-design-of-3-x-sample-pages-for-a-website-379664",
"price": "\u00a3 200 "
}
}, {
"id": 7,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/youtube-channel-art-379663",
"price": "\u00a3 9 "
}
}, {
"id": 8,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pr-events-organisation-source-prizes-for-charity-raffle-379661",
"price": "\u00a3 100 "
}
}, {
"id": 9,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/wordpress-thesis-website-finessing-improve-main-opt-in-des-379659",
"price": "\u00a3 40 "
}
}, {
"id": 10,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-would-like-my-logo-redesigned-updated-379651",
"price": "\u00a3 10 "
}
}, {
"id": 11,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/pattern-maker-pattern-cutter-379650",
"price": " - "
}
}, {
"id": 12,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/add-captcha-379652",
"price": "\u00a3 30 "
}
}, {
"id": 13,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/setup-salesforce-api-so-we-can-just-pull-data-via-rest-379638",
"price": "\u00a3 31 "
}
}, {
"id": 14,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/simple-map-illustration-379643",
"price": "\u00a3 25 "
}
}, {
"id": 15,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/time-lapse-video-for-indoor-construction-project-12-week-p-379637",
"price": "\u00a3 1.0k "
}
}, {
"id": 16,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-asterisk-vicidial-expert-to-help-support-us-379640",
"price": "\u00a3 15 "
}
}, {
"id": 17,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-freelancer-to-provide-help-setting-up-cytoscape-379641",
"price": "\u00a3 21 \/hr"
}
}, {
"id": 18,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/500-word-article-on-business-today-379632",
"price": "\u00a3 12 "
}
}, {
"id": 19,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/web-interface-app-design-379629",
"price": "\u00a3 20 \/hr"
}
}, {
"id": 20,
"info": {
"title": "http:\/\/www.peopleperhour.com\/job\/distribute-leaflets-in-central-birmingham-379630",
"price": "\u00a3 7 \/hr"
}
}]
You can view the current AJAX call on my other question (Link at top of this post).
Could anyone shed some light on how I would decode the JSON array client-side?
I'd like to have a structure like this:
<div class="item">
<div class="title">JSON Title</div>
<div class="price">JSON Price</div>
</div>
Note : from your other question, it is not clear if you always expect a json answer, or if you can receive either of json, html, or xml.
If you always expect json :
$.ajax({ url: ..., data: ...,
dataType: 'json', // <- tell jQuery to expect json,
// and to build a js object from the answer
success : function(obj){
//obj is a regular js object, built from the received json
obj[i].info.title; // <- accessing this piece of data
}
});
If your data is sometimes json, sometimes something else :
success: function(data){
var obj
try {
obj = JSON.parse(data);
// if no exception is thrown, data was a valid json string,
// and obj is a regular js object
obj[i].info.title; // <- accessing this piece of data
} catch (e) {
// Maybe do something on error ?
};
}
You can then build a html string like hsuk suggested :
var html = '';
for(i=0; i < obj.length; i++) {
html += '<div class="item">';
html += '<div class="title">' + obj[i].info.title + '</div>';
html += '<div class="price">' + obj[i].info.price + '</div>';
html += '</div>';
}
alert.html(html).fadeIn();
This is how you do it. What you need is JSON.parse()
test.php
<?php
// Ajax-Server Request Handler
if (isset($_GET['loadData'])) {
exit(json_encode(array(
array(
'id' => 1,
'info' => array('title' => 'http://www.peopleperhour.com/job/amazon-webstore-379672', 'price' => ' - ')
),
array(
'id' => 2,
'info' => array('title' => 'http://www.peopleperhour.com/job/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671', 'price' => '\u00a3 50 ')
),
array(
'id' => 3,
'info' => array('title' => 'http://www.peopleperhour.com/job/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670', 'price' => '\u00a3 50 ')
)
)));
}
?>
<!-- Ajax-Client -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Make Ajax Request
$.get("test.php?loadData", function(data)
{
// Parse Data
var jsonResults = JSON.parse(data);
// Iterate Through Results
$.each(jsonResults, function(key, value)
{
// Display Data
$('.results').append(
'<div class="item" id="'+ value.info.id +'">'+
'<div class="title">'+ value.info.title +'</div>'+
'<div class="price">'+ value.info.price +'</div>'+
'</div>'
);
});
});
});
</script>
<!-- HTML Page - Display Result -->
<div class="results"></div>
Actually, the funny bit about JSON (JavaScript Object Notation) is that you can use it as is in Javascript.
Meaning, if your JSON string is {"foo": "bar"}, you can directly use it in Javascript like:
var myObject = {"foo": "bar"};
or
var myJSONString = '{"foo": "bar"}';
var myObject = eval(myJSONString);
But maybe you better go with JSON.Parse , as eval might be vulnerability if you are parsing User Data, that might not necessarily be in JSON format. (EG. Json data that is sent via HTTP, where the client could mess with ti.)
I have this JSON string in a PHP page:
{
"elements": [{
"type": "pie",
"alpha": 0.3,
"animate": [{
"type": "fade"
}, {
"type": "bounce",
"distance": 5
}],
"start-angle": 0,
"tip": "#val# de #total# #percent#",
"colours": ["#d01f3c", "#356aa0", "#C79810"],
"values": [{
"value": 1,
"label": "procesador amd sempron 140"
}, {
"value": 1,
"label": "procesador sempron le130"
}, {
"value": 1,
"label": "procesador amd a4-3300 x2"
}, {
"value": 1,
"label": "procesador intel celeron g530"
}]
}],
"title": {
"text": "Procesadores, Reinicio",
"style": "color: #356aa0; font-size: 20px"
},
"bg_colour": "#FFFFFF",
"x_axis": null
}
I call it like this:
$.getJSON("restart_proce.php", function(json)
{
console.log(json);
I need to transform it to this:
[{\"value\": 1, \"label\": \"procesador amd sempron 140\" }, { \"value\": 1, \"label\": \"procesador sempron le130\" }, { \"value\": 1, \"label\": \"procesador amd a4-3300 x2\" }, { \"value\": 1, \"label\": \"procesador intel celeron g530\" } ]
I'm trying to delete elements like this:
delete json.elements[3];
but it doesn't delete anything. How can I make it work?
Removing an item from an Array:
There are several ways. The splice method is the most versatile:
data.items.splice(3, 1); // Removes three items starting with the 2nd,
splice modifies the original array, and returns an array of the items you removed.
Try this:
json.elements.splice(3, 1);
See: Array.splice
Just modify the values directly before console.log(json)
json= json.elements[0].values
Or in the restart_proce.php php page just echo
echo json_encode($data['elements'][0]['values']); // if associative array is used.
Try this:
var data = {"result":[
{"FirstName":"Test1","LastName":"User","Email":"test#test.com","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
{"FirstName":"user","LastName":"user","Email":"u#u.com","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
{"FirstName":"Ropbert","LastName":"Jones","Email":"Robert#gmail.com","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
{"FirstName":"hitesh","LastName":"prajapti","Email":"hitesh.prajapati#phptalent.com","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
]
}
alert(data.result);
delete data.result[3];
alert(data.result);
working JSFiddle
or You can use splice to remove elements from an array.
How would I go about selecting the data of each title from the following JSON?
I have the JSON decoded, but I'm not sure how to select the part I want.
{
"responseData": {
"results": [
{
"title": "Justin Giesbrecht 749",
"titleNoFormatting": "Justin Giesbrecht 749",
},
{
"title": "Gopher dunes 09",
"titleNoFormatting": "Gopher dunes 09",
},
{
"title": "dirtbike Justin",
"titleNoFormatting": "dirtbike Justin",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
],
"cursor": {
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
}
],
"estimatedResultCount": "6",
"currentPageIndex": 0,
}
},
"responseDetails": null,
"responseStatus": 200
}
I thought it would be something like this, but I don't get anything:
echo "Response ". $jsonS->responseData->results[1]->title;
Actually you've got the reading of the title part right, it's the JSON that is invalid.
Copying the JSON into a JSON validator/lint e.g. http://www.jsonlint.com/ will show that the you have additional , (commas) after the last object attribute in a few places (5 places to be exact, after each 'titleFormatting' attribute and after 'currentPageIndex').
If you fix those errors and parse it using json_decode e.g.:
$jsonS = json_decode($json_text);
Then your own code:
echo "Response " . $jsonS->responseData->results[1]->title;
Will output the second (index 1 being the second index) results title
Response Gopher dunes 09
When you json_decode something it is converted to a regular PHP array, so you can reference it like $decodedObject["nodeName"].
When I parse that JSON as you quoted it with PHP's json_decode method, it gives me NULL because PHP doesn't think it's valid JSON. Add a var_dump($jsonS); to see if this is happening to you as well. If it is, you may need to be sure your JSON is valid.
Here's what I did, for reference:
$json_data = <<<END_OF_JSON
{
"responseData": { "results": [
{
"title": "Justin Giesbrecht 749", "titleNoFormatting": "Justin Giesbrecht 749",
},
{
"title": "Gopher dunes 09",
"titleNoFormatting": "Gopher dunes 09",
},
{
"title": "dirtbike Justin",
"titleNoFormatting": "dirtbike Justin",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
],
"cursor": {
"pages": [ {
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
}
],
"estimatedResultCount": "6",
"currentPageIndex": 0,
}
},
"responseDetails": null,
"responseStatus": 200
}
END_OF_JSON;
$jsonS = json_decode($json_data);
var_dump($jsonS);
echo "Response ". $jsonS->responseData->results[1]->title;
And the output was:
NULL Response
If you're using different JSON, please edit your question and share it. But if you're actually using the above, it's not valid...
In JSON you are not allowed to leave trailing comma in array/object definition. So, when in PHP is perfectly valid to write:
$a = array(1,2,3,);
(note last comma), in JSON
a : [1,2,3,]
or
a : {x :'y',}
is invalid.