The result of the call to the api server is a json file, which begins with this string:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":[{"packWidth":250,"itemNo"
How do I remove the part that I do not care?
that is, this
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
The complete result is:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result": [{"packWidth":250,"itemNo":"1203945","groupItemNo":"1203945","status":1,"categoryId":105096,"packType":"Color Box","barcode":"6922833439687","modelLabel":"Color","packQty":24,"packInclude":"USB Cable, User Manual, USB Charger, Earphone, 1pcs Li-Battery, LCD Protector, Leather Case, Plastic Case","clearance":false,"id":103928,"packWeight":"12.500","price":"181.2800","packLength":400,"description":"description test","unitWeight":"0.726","packHeight":300}]}}
I use the PHP language
I have to remove the initial part:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
and the final:
}}
If you want to use part of a JSON to populate a CSV file, then parse the json using json_decode method and access the necessary information.
Try something like this:
var jsonObject = json_decode(myJson);
var interestingPart = jsonObject.data.result;
You can now access the data in an Object manner. Or if you want to get a json back from it, then use:
var interestingJson = json_encode(interestingPart);
Not tested, but it should work
preg_replace("/^.*?:(?=\w*\[) | (\w*}\w*}\w*$)/", "", $str);
Edit: i wrote this before I knew of json_decode, you should really use the json functions like suggested in fazovskys answer.
Related
I have a problem with fetching the correct data from a decoded JSON file. I don't know if my question is correct since I don't really know what I am doing for the moment.
So, this is what I don't want to do.
$ln = 'https://api.steamprices.net/v2/csgoprices/?id='.market_hash_name.'&key=XXX';
$link1 = file_get_contents($ln);
$myarray1 = json_decode($link1, true);
echo $myarray1['median_price'];
I am trying to get the price for every steam skin that's being loaded in my code. What this code does is that it loads this api link for every item I load. So if I have 50 items, this link will be loaded 50 times, which is not accepted by the API.
What I want to do, is that I want to load it once, and fetch the prices for every item from that exact link. That link would look like this:
https://api.steamprices.net/v2/csgoprices/?&key=XXX
So, lets say I load it once, and then when I want to apply market_hash_name to it, how do I do?
I assume it is something like this.
$priceJson = file_get_contents('https://api.steamprices.net/v2/csgoprices/?key=XXX');
$priceData = json_decode($priceJson, true);
echo $priceData[''.$market_hash_name.'']['price'];
But it doesn't seem to work. I am sorry for this messy explanation, I an unfamiliar with this.
Note that an example response for the api link looks like this:
{
"-r-H1Z1 Shirt": {
"price": 0.11,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3dxC3m4m0ihzss0MKE6NtIt4qs-JukOX73WgETXYze_pxEBA",
"game": "h1z1"
},
"2016 Invitational Crate": {
"price": 0.09,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6APSjJ6BjX9rGBYZ9ioCPzysSX6hNNacA",
"game": "h1z1"
},
"ANGRYPUG Motorcycle Helmet": {
"price": 0.17,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3WySnxyXoUgz870MKd7sFTkZq98oW1ORiqAVsCUYfbNu3SUQqvUSGyY__iEw",
"game": "h1z1"
},
Another output
{
"name":"Aces High Pin",
"price":1210,
"have":2,
"max":9,
"rate":95,
"tr":0
}
Well, the json string you provide isn't valid but something like this may help you
<?php
$jsonData=file_get_contents("json.file"); // simply contains your json string as posted
$jsonArray=json_decode($jsonData,true);
$jsonObject=json_decode($jsonData);
$list_of_MHN=array("2016 Invitational Crate","ANGRYPUG Motorcycle Helmet");
print_r($jsonArray);
exit;
foreach($jsonArray as $hash_name=>$arr){
if(in_array($hash_name,$list_of_MHN)){
print_r($arr);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonArray[$list_of_MHN[$i]])){
print_r($jsonArray[$list_of_MHN[$i]]);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonObject->$list_of_MHN[$i])){
print_r($jsonObject->$list_of_MHN[$i]);
}
}
?>
I assume some of you might be already rolling their eyes since my topic has been dealt with so often in this forum. However, I haven't found any solution yet in this forum.
I want to parse a JS Object to a receiving PHP Site via JSON. I already read numerous times about the right parameters for the XMLHttpRequest-Header and its impact on the PHP part. I tried the very same solutions given in several other forums, but IT SIMPLY DOESN'T WORK for me. I've been working on this whole issue for four month now. I really need some advice.
Here is my JSON encoding JS Script:
function saveToDB(knotItems) {
var txtobj = knotItems;
var json = JSON.stringify(txtobj);
var url = "http://localhost/projektplaner/tools/DBConnection/writeFileToDB.php";
rq = new XMLHttpRequest();
rq.open("post", url, true);
rq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
rq.send("project=" + json);
rq.onreadystatechange = window.open(url);
}
This is the JS-generated object array knotItems after being stringified by JSON:
[{
"rank": 1,
"name": "Baugrube",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "19.5.2016",
"faz_timestamp": 1463680336402,
"d": "2",
"parallelTask": "seriell",
"fez": ["2016-05-21T17:52:16.402Z", "21.5.2016", "NaN2"],
"fez_dateObj": "2016-05-21T17:52:16.402Z",
"fez_string": "21.5.2016"
}, {
"rank": 2,
"name": "Kellerwände",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "21.5.2016",
"faz_timestamp": 1463853136402,
"d": "4",
"parallelTask": "seriell",
"fez": ["2016-05-25T17:52:16.402Z", "25.5.2016", "NaN4"],
"fez_dateObj": "2016-05-25T17:52:16.402Z",
"fez_string": "25.5.2016"
}, {
"rank": 3,
"name": "Kellerdecke",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "25.5.2016",
"faz_timestamp": 1464198736402,
"d": "5",
"parallelTask": "seriell",
"fez": ["2016-05-30T17:52:16.402Z", "30.5.2016", "NaN5"],
"fez_dateObj": "2016-05-30T17:52:16.402Z",
"fez_string": "30.5.2016"
}]
The reason I post the variable content is to show that all object keys are in double quotes, as required by PHP's json_decode.
This is my PHP receiving script:
if(isset($_POST['project']))
{
echo json_decode($_POST['project'],true);
}
else
{
echo "Keine Daten"; // No Data
}
This is the parameter payload that can be seen via Firebug analysis:
project:"[{"rank":1,"name":"Baugrube","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"19.5.2016","faz_timestamp":1463680336402,"d":"2","parallelTask":"seriell","fez":["2016-05-21T17:52:16.402Z","21.5.2016","NaN2"],"fez_dateObj":"2016-05-21T17:52:16.402Z","fez_string":"21.5.2016"},{"rank":2,"name":"Kellerwände","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"21.5.2016","faz_timestamp":1463853136402,"d":"4","parallelTask":"seriell","fez":["2016-05-25T17:52:16.402Z","25.5.2016","NaN4"],"fez_dateObj":"2016-05-25T17:52:16.402Z","fez_string":"25.5.2016"},{"rank":3,"name":"Kellerdecke","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"25.5.2016","faz_timestamp":1464198736402,"d":"5","parallelTask":"seriell","fez":["2016-05-30T17:52:16.402Z","30.5.2016","NaN5"],"fez_dateObj":"2016-05-30T17:52:16.402Z","fez_string":"30.5.2016"}]"
HTTP Status Code is always 200 (OK).
And this is what I get from the PHP File.
Notice: Undefined index: project in C:\xampp\htdocs\projektplaner\tools\DBConnection\writeFileToDB.php on line 7
Keine Daten
I don't want to sound melodramatic or anything, but I'm about to go ape. I just can't see what the hell is wrong. Could it be a Server configuration issue?
I really, really appreciate your help.
Thank you very much in advance.
I'm trying to decode JSON format
What I am sending is:
{
"id": 123,
"name": "John",
“surname”: “Smith”,
“department”: 3
}
I am sending POST with data via Postman, in the picture.
So, this is the data I want to decode:
"data_serever_received": "{ \"id\": 123, \"name\": \"john\", “surname”: “Smith”, “department”: 3 }"
I tried
$this->input->data["id"]
but it is not working.
How can I get the id, name, surname and etc. values?
Your JSON is invalid “ and ” are not ".
(Zoom in with your browser if you can't see the difference).
You need to start with valid JSON before you can parse it.
You can use json_decode to make it an array.
$json_array = json_decode($json_object);//$json_object will need to contain your json string.
then you can access like this:
echo $json_array["data"][“surname”];
PHP Doc on json_decode: http://php.net/manual/en/function.json-decode.php
I'm getting this kind of response from instagram server.
{
"meta": {
"code": 200
},
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}
How do I get the "data" - part? I've tried to json decoding in PHP like:
//$userfeed is giving me something like above.
$tried_this = json_decode($userfeed['meta']);
but $userfeed and $tried_this seems to be the same.
UPDATE
Down below is the REAL data...
I've left out the access token, but otherwise it's correct. This is just a part of it, but I hope you get the picture....
{"pagination":{"next_url":"https://api.instagram.com/v1/users/3/media/recent?access_token=blablabla\u0026max_id=622063574553989866_3","next_max_id":"622063574553989866_3"},"meta":{"code":200},"data":[{"attribution":null,"tags":[],"type":"image","location":{"latitude":21.367158921,"name":"Pali
Lookout","longitude":-157.79304912,"id":60507},"comments":{"count":313,"data":[{"created_time":"1401835727","text":"Can
you give me a shout
out","from":{"username":"nick_putukian1","profile_picture":"http://images.ak.instagram.com/profiles/profile_1370615750_75sq_1401835573.jpg","id":"1370615750","full_name":"Nicholas
Putukian"},"id":"734973811849433422"},{"created_time":"1401836165","text":"I
only have one
follower","from":{"username":"nick_putukian1","profile_picture":"http://images.ak.instagram.com/profiles/profile_1370615750_75sq_1401835573.jpg","id":"1370615750","full_name":"Nicholas
Putukian"},"id":"734977485287985692"},{"created_time":"1401837312","text":"Dear
#kevin could u please add share feature on IG? So users don't have to
screenshoot a foto first if we want to share it.
Thanks.","from":{"username":"natalia.igaa","profile_picture":"http://images.ak.instagram.com/profiles/profile_1003500786_75sq_1401603184.jpg","id":"1003500786","full_name":"Ayu
Natalia"},"id":"734987110351638699"},{"created_time":"1401837882","text":"HI
KEVIN","from":{"username":"gildathegriffon","profile_picture":"http://images.ak.instagram.com/profiles/profile_320785380_75sq_1401742420.jpg","id":"320785380","full_name":"Doivid"},"id":"734991884560110057"},{"created_time":"1401838561","text":"\ud83d\ude02\ud83d\ude02\ud83c\udf42\ud83d\udc9
Forgive me for not giving you a "readable" var_dump, but for some reason the var_dump on a specific server I'm trying on doesn't make it readable as expected.
$data = json_decode($userfeed, true);
var_dump($data['data']);
is returning NULL
Assuming, a valid JSON string, you would do:
$data = json_decode($json_string, true);
var_dump($data['data']);
Lets assume that you have provided access_token, than following syntax will meet your requirements
$url = "https://api.instagram.com/v1/users/3/media/recent/?access_token=ACCESS-TOKEN";
$content = file_get_contents($url);
$data = json_decode($content, true);
var_dump($data['data']);
My first JSON is:
{
"categoryId":"Painting",
"subCategoryId":"Residential",
"alternatives": [1,2,3,4,5],
"criterias":["price","quantity","yom","company"],
"answers":[["1000","12343","4543","","4645646"],["12","23","34","","45"],["2014","","2000","1990","2005"],["xyz","","Abc","jkl","mno"]]
}
This will come from a java URL, here I am using PHP, in PHP I am calling a java URL.
My Second JSON is:
{"criterias":"Location"}
I am generating this using JQuery.
How can I include the second JSON into the first JSON criterias?
The simplest way to include one file in another is to use cpp (C preprocessor).
For example, if I have test.json as
{"name":"NAME",
#include "another.json"
}
and another.json as
"inner":"value"
you should be able to obtain
$ cpp -P test.json
{"name":"NAME",
"inner":"value"
}
Of course, you will need to make sure that resulting syntax is correct by properly formatting both pieces.
I believe the original question is how to merge these 2 JSON objects within javascript. Assuming that, the answer is simple.
var firstJson = {
"categoryId":"Painting",
"subCategoryId":"Residential",
"alternatives": [1,2,3,4,5],
"criterias":["price","quantity","yom","company"],
"answerss":[["1000","12343","4543","","4645646"],["12","23","34","","45"],["2014","","2000","1990","2005"],["xyz","","Abc","jkl","mno"]]
};
var secondJson = {"criterias":"Location"};
firstJson.criterias = $.extend({},firstJson.criterias,secondJson.criterias);
You need to convert your first JSON string to object and add a new property to it.
If it is Java, you can use Google's Gson library
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
jsonObj.add("criterias", "Location");
If it is JavaScript,
var jObj = JSON.parse(jsonString);
jObj.criterias = "Location"; //jObj.NewItem = "NewValue";
Here is the example of how you write nested JSON
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
For More examples visit following links:
http://www.jsonexample.com/
http://json.org/example
create nested JSON object in php?