How to turn JSON to object literal using PHP and jquery - php

Is there a concise neat way to turn an XML feed into an JavaScript object literal?
I have this XML feed
<jobs>
<industry>
<name>Technology</name>
<area>Refrigiration</area>
<area>Information Technology</area>
<area>Electronics</area>
<area>Avionics</area>
</industry>
<industry>
<name>Agriculture</name>
<area>Agri-Tourism</area>
<area>Animal Husbandry</area>
<area>Harvesting</area>
<area>Poultry</area>
</industry>
</jobs>
and wish to turn it to:
var jobs = [
{
"name" : "Technology",
"areas" : [ "Refrigiration" , "Information Technology", "Electronics", "Avionics" ]
},
{
"name" : "Agriculture",
"areas" : [ "Agri-Tourism" , "Animal Husbandry", "Harvesting", "Poultry" ]
},
{
"name" : "Media",
"areas" : [ "Journalism" , "Camera person", "Reality tv person", "Commentator" ]
}
];
I succeeded in encoding the JSON object using php. What I am missing is the rest.

echo json_encode(simplexml_load_string("<jobs>
<industry>
<name>Technology</name>
<area>Refrigiration</area>
<area>Information Technology</area>
<area>Electronics</area>
<area>Avionics</area>
</industry>
<industry>
<name>Agriculture</name>
<area>Agri-Tourism</area>
<area>Animal Husbandry</area>
<area>Harvesting</area>
<area>Poultry</area>
</industry>
</jobs>"));
This gives you:
{
"industry": [
{
"name": "Technology",
"area": [
"Refrigiration",
"Information Technology",
"Electronics",
"Avionics"
]
},
{
"name": "Agriculture",
"area": [
"Agri-Tourism",
"Animal Husbandry",
"Harvesting",
"Poultry"
]
}
]
}

You need to convert your XML to an array, https://stackoverflow.com/questions/4844476/xml-to-php-array
Then you'll need to convert the array to json using php json_encode()

If you are receiving a JSON encoded string in your javascript callback, you probably need to run $.parseJSON() to make jQuery treat it as a JSON object instead of a string

Two solutions:
PURE JQUERY
Using jQuery's parseXML , combined with jQuery get you can have the object you need:
$.get("http://www.example.com/path/to/file.xml", function(data){
var xml = $.parseXML(data);
console.log(xml);
});
PHP+JQUERY
if you've already parsed the object into a json, just print it into an html file and get that file using jquery's getJSON
$.getJSON("http://www.example.com/json/feed",function(data){
console.log(data);
});

Related

I want a more consolidate json format

I am getting json array after getting applying query logic.
[
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-20"
},
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "CRP",
"booking_date": "2018-05-20"
},
{
"id": "4",
"diag_name": "Seepz Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-21"
}
]
But i want a more justified json array written below.
[
{
"diag_name": "LT Diagnostics",
"test_name": [
{
"id": "3",
"name" : "Alk PO4"
},
{
"id": "3",
"name" : "CRP"
}
],
"booking_date": "2018-05-20"
},
{
"diag_name": "Seepz Diagnostics",
"test_name": [
{
"id": "4",
"name" : "Alk PO4"
}
],
"booking_date": "2018-05-21"
},
]
I am not getting it,How to do in php. I want a more consolidate json format.
Have you tried changing your SQL query to group by diag_name and booking_date? That would be the first step I’d employ to get the outer data.
Formatting the data in the nested manner you’re after could be a function of whatever record serializer you’re using — does it support nested JSON as a return type, or only flat JSON as your example return value shows?
If the record set -> JSON serializer only ever returns flat data, the comments above are correct that you will have to write your own formatter to change the shape of the JSON yourself...
The accepted answer of this other question may be of help:
Create multi-level JSON with PHP and MySQL
I'm not a PHP guy but this is a typical scenario to use functional programming by means of the monad Map.
Looking online I've found this article that could help you.
Changing datasource output is not always (seldom indeed) a viable option.
Enjoy coding

json decode and get value using PHP

I have a JSON string and i want to get the value.
$s='{
"subscriptionId" : "51c04a21d714fb3b37d7d5a7",
"originator" : "localhost",
"contextResponses" : [
{
"contextElement" : {
"attributes" : [
{
"name" : "temperature",
"type" : "centigrade",
"value" : "26.5"
}
],
"type" : "Room",
"isPattern" : "false",
"id" : "Room1"
},
"statusCode" : {
"code" : "200",
"reasonPhrase" : "OK"
}
}
]
}';
Here is the code which I used but it didn't work.
$result = json_decode($s,TRUE); //decode json string
$b=$result ['contextResponses']['contextElement']['value']; //get the value????
echo $b;
ContextResponses contains a numerically indexed array (of only one item) and value property is more deeply nested than what you are trying to reference (it is within attributes array). This would appear to be what you need:
$b = $result['contextResponses'][0]['contextElement']['attributes'][0]['value'];
When reading a JSON-serialiazed data structure like that, you need to make sure and note every opening [ or { as they have significant meaning in regards to how you need to reference the items that follow it. You also may want to consider using something like var_dump($result) in your investigations, as this will show you the structure of the data after it has been deserialized, oftentimes making it easier to understand.
Also, proper indention when looking at something like this would help. Use something like http://jsonlint.com to copy/paste your JSON for easy reformatting. If you had your structure like the following, nesting levels become more readily apparent.
{
"subscriptionId": "51c04a21d714fb3b37d7d5a7",
"originator": "localhost",
"contextResponses": [
{
"contextElement": {
"attributes": [
{
"name": "temperature",
"type": "centigrade",
"value": "26.5"
}
],
"type": "Room",
"isPattern": "false",
"id": "Room1"
},
"statusCode": {
"code": "200",
"reasonPhrase": "OK"
}
}
]
}

Parse curl response from github api

I'm a newbie in php but I'm trying to learn right now. What i want to make :
Send a curl request to github api like this :
curl_setopt($ch, CURLOPT_URL, 'https://api.github.com/legacy/repos/search/language:' . $lang);
And when i receive the result to display like a nice html page. The response that I'm receiving right now is displayed like the one written in github api documentation http://developer.github.com/v3/search/.
This is the first time I'm trying to learn PHP, but not the first time I've been web developing ( I've been contributing to a Hakyll based blog these weeks ).
My question is : How could i parse the results to format them nicely in a html page ?
The results are returned via JSON. You can make use of json_decode() for that.
Pass your cURL $response to this function. Such that print_r(json_decode($response,1));
Example of how to do it
<?php
$json='{
"text_matches": [
{
"object_url": "https://api.github.com/repositories/3081286",
"object_type": "Repository",
"property": "name",
"fragment": "Tetris",
"matches": [
{
"text": "Tetris",
"indices": [
0,
6
]
}
]
},
{
"object_url": "https://api.github.com/repositories/3081286",
"object_type": "Repository",
"property": "description",
"fragment": "A C implementation of Tetris using Pennsim through LC4",
"matches": [
{
"text": "Tetris",
"indices": [
22,
28
]
}
]
}
]
}';
$jarr=json_decode($json,1);
echo $jarr['text_matches'][0]['object_url']; //"prints" https://api.github.com/repositories/3081286

Textarea list via jquery .ajax to php

I have a textarea that I want to submit via ajax. When I try to output the value, I only get [object Object]
Jquery (ajax)
$("#insertAddresses").click(function() {
$.ajax({
type: "POST",
url: "insertAddr.php",
data: 'addresses=' +
}).done(function(list) {
//getList(); // run query to get addresses and populate list
});
});
PHP (i've tried)
$_POST['addresses'];
or
$addresses = explode("\n", $_POST['addresses']);
Regardless of anything i've tried, always returns
[object Object]
Help?!
Your serverscript is returning a json object, which is correctly recognized by JavaScript as an object. You can do a whole lot of things with that object, but you can't just put it on your website, as it is not html or text.
Here is a short description of json: http://en.wikipedia.org/wiki/JSON
I don't know how your data is structured, so i can't tell you how you can access your data. But in a json like this (example from wikipedia):
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
}
You could, ie., excess the firstName simply with:
data.firstName
An voila, there is your excpected data.
You're data should be an object:
data: { adresses: "value" }
Just a little tip: the shorthand ajax-call for what you're doing in jQuery is $.post(.... and then you can lose the "type". Does exactly the same, but I think it's just a little neater.

Help with some json data and php

I just need a little help with json and php. How do i echo certian parts of data if my request comes back looking like this:
{ "data": { "current_condition": [ {"cloudcover": "2", "humidity": "54", "observation_time": "09:05 PM", "precipMM": "0.0", "pressure": "1019", "temp_C": "11", "visibility": "10", "weatherCode": "113", "weatherDesc": [ {"value": "Clear" } ], "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png" } ], "winddir16Point": "N", "winddirDegree": "350", "windspeedKmph": "15", "windspeedMiles": "9" } ], "request": [ {"query": "48.85,2.35", "type": "LatLon" } ] }}
I am using a weather API, my code currently looks like:
$weather_url = file_get_contents("http://free.worldweatheronline.com/feed/weather.ashx?q=xxxxx&format=json&num_of_days=2&key=xxxxxxxxxxxxxxxxxx");
$json_output_w = json_decode($weather_url, true);
the q in the url string can be a zipcode, lat and long, or a city, i know it is returning data because i can dump the variable $json_output_w; but i just need a little guidance as how to actually echo certain parts of the data that is returned. like say i wanted to echo
windspeedMiles
The json_decode() function will return either an object or array (depending on the second argument). You can explore the structure of the returned item using the var_dump() function:
var_dump( $json_output_w );
From here you would discover what type of structure you need to consider when pulling values out. To get the windSpeedMiles value, you'd do the following:
echo $json_output_w["data"]["current_condition"][0]["windspeedMiles"];
Online Demo: http://codepad.org/BfhHbQMz

Categories