Decode json PHP find output only arrays containing POST string value - javascript

Im trying to make a simple JSON retriever.
So here is what im trying to do.
When i type for example
Japan. and i post the data to php.
I want it to load the json it has and search arrays for values containing this country Japan
Sending a smaller cut down json array containing only results containing this value back to the page.
The key is Country,
Example json
{
"1": {
"country": "America",
"Name": "Harry",
"Age": "41"
},
"2": {
"country": "America",
"Name": "ben",
"Age": "40"
},
"3": {
"country": "Japan",
"Name": "taka",
"Age": "48"
},
"4": {
"country": "Japan",
"Name": "John",
"Age": "41"
},
"5": {
"country": "America",
"Name": "Ted",
"Age": "41"
},
"6": {
"country": "America",
"Name": "Simon",
"Age": "41"
}
}
var country = $(".country").val();
$.ajax ({
url: json.php,
type: 'POST',
data: {
'find': country,
},
success: function (results) {
console.log(results);
},
fail: function(data) {
console.log( data.responseText );
console.log( 'Request Failed' + data.statusText );
}
})
<input name="country" class="country" type="text" placeholder="type country"></input>
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$jsonurl = "data.json";
$json = file_get_contents($jsonurl);
$find = $_POST["find"];
$decode = json_decode($json, true);
$results = array_filter($decode[''], function($country) {
return $country['country'] == $find;
});
var_dump($results);
Any help would be appreciated...

Here is the code sample using which you can achieve your requirement.
$my_json = '{
"1": {"country": "America","Name": "Harry","Age": "41"},
"2": {"country": "America","Name": "ben","Age": "40"},
"3": {"country": "Japan","Name": "taka","Age": "48"},
"4": {"country": "Japan","Name": "John","Age": "41"},
"5": {"country": "America","Name": "Ted","Age": "41"},
"6": {"country": "America","Name": "Simon","Age": "41"}
}';
$json_arr = json_decode($my_json);
$item = array();
foreach($j as $k=>$struct) {
if ('Japan' == $struct->country) {
$item[$k] = $struct;
}
}
echo 'Object Array form::';
echo '---------------------------';
print_r(array_values($item));
echo 'Json form::';
echo '---------------------------';
echo json_encode(array_values($item));

Related

How can I concatenate this type of JSON in javascript?

How can I concatenate this json to obtain it:
complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ?
Each address can contain a set of complements which must be concatenated and separated by a comma.
P.s: I'm using javascript.
P.s2: Complements can be null like in the second group in JSON.
[
{
"postalcode": "1234",
"street": "ABC",
"number": "1",
"complement": [
{
"type": "B",
"name": "XYZ",
"description": "3"
},
{
"type": "C",
"name": "CDE",
"description": "TR"
},
{
"type": "D",
"name": "AAA",
"description": "5"
}
]
},
{
"postalcode": "444",
"street": "No complements",
"number": "5"
},
{
"postalcode": "2222",
"street": "BBB",
"number": "2",
"complement": [
{
"type": "E",
"name": "NDP",
"description": "3"
},
{
"type": "F",
"name": "DDD",
"description": "FR"
}
]
}
];
My code I'm getting this.complementsList.forEach is not a function.
getComplement(addressesResponse){
this.complementsList = JSON.parse(addressesResponse);
this.complementsList.forEach((item) => {
Object.defineProperty(item, 'complements', {
get: function() {
return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
})
});
Source: https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc
how i solved it :
arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');
Having a javascript object, you can go through the keys of the object and combine some of them into strings
It will look something like this:
const jsonObject = [{...}, {...}, ...]
const complements = [];
jsonObject.forEach((item) => {
let complement = item['complement'].reduce((result, currObj)
=> result += (currObj.name+' '+currObj.description), "");
complements.push(complement);
});
This is just an example. There are many ways to do it.

Remove JSON parent element in JavaScript

I'm currently trying to code an application with javascript. It pulls data from a database and the response I'm getting is something like that:
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
But I need to have the JSON like that:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
How can I delete the parent values object in my JSON?
SHORT ANSWER:
Just access the values property like a JavaScript object.
LONG ANSWER:
You didn't post the JavaScript code snippet so it's quite difficult to give you an appropriate answer.
Assuming you have the following code:
const jsonString = getDataFromTheDB()
const jsonObject = JSON.parse(jsonObject) // still has the "values" layer
const values = jsonObject.values // what you want, without the "values" layer
// BONUS: Just in case you want to convert the object back to a JSON string but without the "values" layer
const valuesJSON = JSON.stringify(values, undefined, 2)
Based on this post :
just do this (consider json the variable that contains your json):
var key = "values";
var results = json[key];
delete json[key];
json = results;
console.log(json) will output the following:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
But you dont even have to do the last 2 steps of the code snippet above, you could also just directly use results variable and have the same output by console.log(results).
You could take the object and create a new variable with just the array.
var vals =
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
var arr = vals.values;
console.log(arr);

how to parse this kind of json array

I have a json array like blew :
{
"0": {
"kind": "mammal",
"name": "Pussy the Cat",
"weight": "12kg",
"age": "5"
},
"1": {
"kind": "mammal",
"name": "Roxy the Dog",
"weight": "25kg",
"age": "8"
},
"2": {
"kind": "fish",
"name": "Piranha the Fish",
"weight": "1kg",
"age": "1"
},
"3": {
"kind": "bird",
"name": "Einstein the Parrot",
"weight": "0.5kg",
"age": "4"
}
}
i removed an element 'Piranha the Fish' With (UNSET) My json code changed to blow:
{
"0": {
"kind": "mammal",
"name": "Pussy the Cat",
"weight": "12kg",
"age": "5"
},
"1": {
"kind": "mammal",
"name": "Roxy the Dog",
"weight": "25kg",
"age": "8"
},
"3": {
"kind": "bird",
"name": "Einstein the Parrot",
"weight": "0.5kg",
"age": "4"
}
}
when I remove element the counter of the element change to 0,1,3
so now i can't to have full access in my json elements
I want echo value with this code :
for ($i = 0; $i < $JsonCount - 1; $i++) {
echo "Name :";
echo $json_cod[$i]['name'];
echo "<br/>";
echo "Age :";
echo $json_cod[$i]['age'];
echo "<br/>";
}
out put :
Name :Pussy the Cat
Age :5
Name :Roxy the Dog
Age :8
Try using foreach.
foreach ($json_cod as $item) {
echo "Name :";echo $item['name'];echo "<br/>";
echo "Age :";echo $item['age'];echo "<br/>";
}
If you want to use your code to echo ,after deleting a value from array use $newarray=array_values($oldarray) to reindex the array.
That is because unset() remove the value along with the key/index from the array and left it as it is,i.e it does not rearrange the key/index.
If you want to rearrange key the use array_slice() instead See array_slice. and you will get what you want. You will be able to do
for($i=0; $i <$JsonCount-1 ; $i++)
{
echo "Name :";echo $json_cod[$i]['name'];echo "<br/>";
echo "Age :";echo $json_cod[$i]['age'];echo "<br/>";
}

How to query a json file?

Here is the file I would like to parse
I receive a file from a webservice in JSON format.
I would like to parse the content in such a way that I display the name of the president from the USA
{
"response": {
"result": {
"Countries": {
"row": [
{
"no": "1",
"FL": [
{
"content": "USA",
"val": "Country"
},
{
"content": "Barack Obama",
"val": "President"
}
]
},
{
"no": "2",
"FL": [
{
"content": "Cuba",
"val": "Country"
},
{
"content": "Raul Castro",
"val": "President"
}
]
}
]
}
}
}
}
The expected output
{ presidents: [
{ "name": "Barack Obama"}
]
}
could you provide a solution using a kind of JSON XPath?
Assuming that you are loading the response into a variable data:
var data = {
"response" : {
"result" : {
"Countries" : {
"row" : [{
"no" : "1",
"FL" : [{
"content" : "USA",
"val" : "Country"
}, {
"content" : "Barack Obama",
"val" : "President"
}
]
}, {
"no" : "2",
"FL" : [{
"content" : "Cuba",
"val" : "Country"
}, {
"content" : "Raul Castro",
"val" : "President"
}
]
}
]
}
}
}
};
You can then filter your data like this:
data.response.result.Countries.row.filter(function (el) {
return (el.FL[0].content == "USA");
})[0].FL[1];
To get to:
{
"content" : "Barack Obama",
"val" : "President"
}
To get the name, simply specify "content"
data.response.result.Countries.row.filter(function(el){
return (el.FL[0].content == "USA");
})[0].FL[1].content;
EDIT 1
One could search a json object like a string.
If we know that the element will have no children, then we could use something like this:
function find(query,obj) {
var str = JSON.stringify(obj);
var start = str.substr(0,str.indexOf(query)).lastIndexOf('{');
var end = str.substr(start,str.length).indexOf('}');
return str.substr(start,end);
}
console.log(find('"content":"USA"',data))
Despite of the age of the question I want to add this answer as reference for future visitors with the same problem:
You can use JSONPath. The page contains a description and an implementation in JavaScript and PHP.
t = {
"response": {
"result": {
"Countries": {
"row": [
{
"no": "1",
"FL": [
{
"content": "USA",
"val": "Country"
},
{
"content": "Barack Obama",
"val": "President"
}
]
},
{
"no": "2",
"FL": [
{
"content": "Cuba",
"val": "Country"
},
{
"content": "Raul Castro",
"val": "President"
}
]
}
]
}
}
}
}
res={};//Here we will store result
for (i in t.response.result.Countries.row) {
// get current country
country = t.response.result.Countries.row[i].FL[0].content;
// get current president
president = t.response.result.Countries.row[i].FL[1].content;
if (country == 'USA') {
res.presidents=[{name:president}];
break;
}
}

Retrieving and displaying JSON data from URL

I am trying to retrieve and display information about current weather from a JSON object using javascript and a URL request:
http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805'
the data from the URL looks like this:
{
"data": {
"current_condition": [
{
"cloudcover": "75",
"humidity": "88",
"observation_time": "03:30 PM",
"precipMM": "2.7",
"pressure": "1008",
"temp_C": "12",
"temp_F": "54",
"visibility": "8",
"weatherCode": "302",
"weatherDesc": [
{
"value": "Moderate rain"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0018_cloudy_with_heavy_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "140",
"windspeedKmph": "17",
"windspeedMiles": "11"
}
],
"request": [
{
"query": "DE3",
"type": "Postcode"
}
],
"weather": [
{
"date": "2012-05-09",
"precipMM": "11.8",
"tempMaxC": "13",
"tempMaxF": "56",
"tempMinC": "12",
"tempMinF": "53",
"weatherCode": "266",
"weatherDesc": [
{
"value": "Light drizzle"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "141",
"winddirection": "SE",
"windspeedKmph": "12",
"windspeedMiles": "7"
},
{
"date": "2012-05-10",
"precipMM": "11.1",
"tempMaxC": "18",
"tempMaxF": "64",
"tempMinC": "6",
"tempMinF": "43",
"weatherCode": "353",
"weatherDesc": [
{
"value": "Light rain shower"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png"
}
],
"winddir16Point": "SSW",
"winddirDegree": "209",
"winddirection": "SSW",
"windspeedKmph": "30",
"windspeedMiles": "19"
}
]
}
}
I have tried a couple of scripts to try and get the data and take bits out to display in a div. The first one looks like this:
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805"
dataType: 'json',
success: function(data) {
jQuery.each(data, function() {
alert("HELLO");
alert("Current Cloud Cover = " + this.data.current_condition.cloudcover);
alert("Current Humidity = " + this.data.current_condition.humidity);
});
}
});
the second one looks like this:
var postcode = document.getElementById("address").value;
function getWeather(userName, count) {
$.getJSON(
'http://free.worldweatheronline.com/feed/weather.ashx?q' + postcode + '&format=json&num_of_days=2&key=ec9c2dc5ba201904120805',
{},
showWeather,
//'jsonp'
);
}
function showWeather(day) {
var str = '<ul>';
str += '<h2>Tweets from ' + postcode + '</h2>';
var i = 0;
$.each(day, function(index, value) {
if (i == count) return;
var dt = new Date(value.date);
str += '<p>';
str += value.temp_C; //gets "text" from JSON
str += '</p>';
str += '';
str += '';
i++;
});
}
I want to get the weather information from the JSON URL and display some of the information in a div, can anybody explain how to do this is these two scripts dont work.
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805",
dataType: 'jsonp', // You need to use 'jsonp' here because it is cross domain request
success: function(data) {
$.each(data, function(index, value) {
alert(value.current_condition[0].cloudcover);
alert(value.current_condition[0].humidity);
alert(value.current_condition[0].weatherDesc[0].value);
alert(value.request[0].query);
alert(value.request[0].query);
$.each(value.weather, function(i, val) {
alert(val.precipMM);
alert(val.weatherDesc[0].value);
})
});
}
});
DEMO
There are a few problems... the following should work (modification of the first block of code).
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805&callback=?",
dataType: 'jsonp',
success: function(data){
jQuery.each(data, function(){
alert(JSON.stringify(this));
alert("Current Cloud Cover = " + this.current_condition[0].cloudcover);
alert("Current Humidity = " + this.current_condition[0].humidity);
});
}
});
To recap:
You need to use JsonP to circumvent cross-site-scripting restrictions (do that by adding "&callback=?" to the AJAX URL.
The root of the JSON response is data, so you need to write data.data.
The current_condition property is an array-- have to add an indexer (ie, [0]) to access it.

Categories