Parsing JSON string to dictionary swift - php

I'm trying to access the individual member-fields of a JSON object in PHP from a JSON string but I can't to access the inner-json, all I get is Array.
This is the JSON string
data = (
{
"created_time" = "2018-10-07T04:42:39+0000";
id = 1069496473131329;
name = "NAME_0";
},
{
"created_time" = "2018-09-09T10:31:50+0000";
id = 955684974605664;
name = "NAME_1";
},
At the moment my code is:
$nameString = $_POST["nameData"];
$nameJsonString = json_encode($nameString, JSON_FORCE_OBJECT);
$jsonNameObj = json_decode($nameJsonString, true);
I've been trying to access the individual entry with:
$element = $jsonNameObj['data'][0];
But only receive Array.
Any help would be greatly appreciated,
Cheers :)

After checking the inputted JSON data, I've realised that it doesn't have a consistent form. As opposed to the overall structure being:
JSON -> List -> JSON
Instead, it's:
JSON -> List
The list contains individual elements that can be in a different order. Consequently, calling:
$element = $jsonNameObj['data'][0]['created_time'];
Works sometimes. As there are three-values/object, I can congregate these values into a trio.
I'm sure there's a way to condense this list into a fixed-JSON format but I'm not familiar with how I'd go about that.
At the moment, with a bit of logic on the back-end, I can retrieve the values.
Thanks for your help #Difster and #Osama!

Related

How to extract data from this code (never seen this format before)?

I am using a plugin in my wordpress that stores my data in a specific way. I have a problem on how to extract that data into an array using php. The data currently saved in database is in this kind of format which i have never seen before. I want to get the name, price and the referral amount from this data.
I have tried using php foreach looping to extract data but it wont recognize the foreach function.
a:2:{i:0;a:4:s:4:"name";s:14:"Tower";s:2:"id";i:4177;s:5:"price";i:500;s:15:"referral_amount";s:3:"20";}i:1;a:4:s:4:"name";s:25:"Square";s:2:"id";i:3998;s:5:"price";i:178;s:15:"referral_amount";s:4:"87.4";}}
I wanted the array to store the data in this kind of way:
{
name:'Tower',
price:500,
referral_amount:20,
}
Does anyone knew how to extract this kind of data using php?
$data = 'a:2:{i:0;a:4:{s:4:"name";s:14:"Tower";s:2:"id";i:4177;s:5:"price";i:500;s:15:"referral_amount";s:3:"20";}i:1;a:4:{s:4:"name";s:25:"Square";s:2:"id";i:3998;s:5:"price";i:178;s:15:"referral_amount";s:4:"87.4";}}';
$data = preg_replace_callback('!s:(\d+):"(.*?)";!',
function ($match) {
return 's:'.strlen($match[2]).':"'.$match[2].'";';
},
$data);
$data_array = unserialize($data);
$final_data = json_encode($data_array);
echo $final_data;

Json string conversion to json object

I have been stuck in this issue and cant seem to fix it.. I have this JSON STRING
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
I need to convert it into array of object or maybe just one json object.. I have tried doing
json_decode($unBilledArr , true);
It gives me null.
Already tried these solutions as well
Convert a string to JSON object php
https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
I must be doing something wrong.. cant seem to figure out what..
P.s : This is the response i am getting and i can not do anything about the response.
You are trying to decode an array, either specify the specific item within the array, or make it a string.
For instance:
$unBillableArr = '{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}';
$json = json_decode($unBillableArr, true);
// Or
$unBillableArr = ['{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}'];
$json = json_decode($unBillableArr[0], true);
However, given the string you are receiving does not contain valid JSON and you are unable to control what you receive, I have prepared the following that will replace the single quotes in your JSON, and decode each item into an array:
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
// Loop through each JSON string
$jsonObjects = []; // Change this name...
foreach ($unBillableArr as $jsonString) {
$jsonObjects[] = json_decode(str_replace("'", '"', $jsonString), true);
}
print_r($jsonObjects); // Proof it works
Please bear in mind that I would consider this to be a dirty fix. To fix this properly, you should go back to the source and ensure that the JSON they are returning to you is valid.

Scraping data from php file

I am trying to get the car positions (if I can the cars state (gas, how clean, etc) from this site: https://carsharing.mvg-mobil.de/?ref=separate.
As far as I can tell they get their data from this URL:
https://carsharing.mvg-mobil.de/json/stations.php
Now I am having trouble converting that into usable XML format. I tried bringing it into String form by using
JSON.stringify()
and go from there but that didn't seem to work. What im having trouble with are the { and quotation marks
since your question is tagged as php, here is a simple code-snippet that will get you a xml-string:
<?php
//get json-string
$cars_json = file_get_contents("https://carsharing.mvg-mobil.de/json/stations.php");
//convert json to array
$cars_array = json_decode($cars_json,true);
//creat xml-object and fill recursive
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($cars_array, array ($xml, 'addChild'));
//create xml-string that can be saved
$cars_xmlstring = $xml->asXML();
echo $cars_xmlstring
?>

How to read complex data in array/JSON with PHP?

I've been facing really hard times to read a bunch of data in JSON using json_decode() function in PHP. Basically I need to read basic data to display flights dates origins and destinations.
This is how it should be:
20 solutions found.
Solution# 1 Sale Price: BRL2919.54
Slice 0
TA 916 GRU 2015-06-16T06:15-03:00 LIM 2015-06-16T09:20-05:00
AV 962 LIM 2015-06-16T10:04-05:00 MIA 2015-06-16T16:48-04:00
And this is the JSON code: http://pastebin.com/dH16RriT
When I try to transform that and read it comes with NULL data.
$data = json_decode($results, true); // $results is a variable with
the JSON content from the URL above
echo $data['tripOption']['saleTotal']; // just an example
yes , you should use
print_r($a['trips']['tripOption'][0]['saleTotal'])
if you want to read the data inside that array,you can do as follows:
$data = json_decode($s,true);
foreach ($data['trips']['tripOption'] as $item){
print_r($item['saleTotal'] . "\n");
};
I have no problem to decode that data from the json structure you posted. Here is a trivial example script which dumped the decoded array structure:
<?php
$json = file_get_contents('./data.json');
$data = json_decode($json, true);
print_r($data);
About the specific data you try and fail to extract: you have to take care to use the correct "path" inside the data structure. This one works:
print_r($data['trips']['tripOption']);
Since that one is an array yo have to address a specific entry in there to get the output you expect:
echo $data['trips']['tripOption'][0]['saleTotal']; // just an example

JSON PHP: Is this the correct way?

I just wanted some input about my use of JSON.
<?php
header('Content-Type: text/plain');
//results
$results = array();
for($i=0;$i<20;$i++)
{
$result = array();
$result['name'] = 'Test Season '.ceil(($i+1)/13).' Episode '.(($i%13)+1);
//$result['torrent'] = 'https://www.example.com/?id='.$i.'&key='.uniqid();
$result['torrents'] = array();
$c = mt_rand(1,4);
for($j=0;$j<$c;$j++)
{
$torrent = array();
$torrent['url'] = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent['codec'] = $j%2 == 0 ? 'xvid' : 'h264';
$torrent['resolution'] = '720p';
$result['torrents'][] = $torrent;
}
$results[] = $result; //push
}
echo json_encode($results);
?>
This is just some test code, not an actual implementation. Am I using JSON correctly and too the fullest? Or is some better method of doing this?
I have legal torrents that I'd like to do some JSON with.
Torrents are grouped by name which contain multiple torrents (actual links to data). And other information such as codec etc.
This is my first time actually outputting JSON, would XML be better?
Are there any guides on this topic (hopefully not entire books)?
Thanks.
What you doing is right. I like to use the StdClass to make objects rather than key value arrays, just cause it looks sexier! E.g.
$torrent = new StdClass();
$torrent->url = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent->codec = $j%2 == 0 ? 'xvid' : 'h264';
$torrent->resolution = '720p';
$result['torrents'][] = $torrent;
As you say you don't need to read a whole book on the matter, I would have a look here http://php.net/manual/en/book.json.php to get to grips with the basics of JSON.
In terms of JSON vs XML, I find it far easier to represent data as JSON as it is easier to fetch the specific data you want much in the same way you can access the info in a stdClass object.
[EDIT]
And as Stefan Gehrig says make sure you define your content type as "application/json".
Absolutely fine. You could only change the MIME type to be RFC 4627 compliant though: application/json.

Categories