Converting NSArray - JSON - NSData - PHP server -JSON representation
Turns out I needed to do it like this:
To Create My data:
NSMutableArray *arrayOfDicts = [[NSMutableArray alloc] init];
for (int i = 0; i < 2; i++) {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"MySong", @"title",
@"MyArtist", @"artist",
nil];
[arrayOfDicts addObject:dict];
}
NSArray *info = [NSArray arrayWithArray:arrayOfDicts];
And Sent it like this:NSData *jsonData = [NSJSONSerialization dataWithJSONObject:info
options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Start request
NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/index.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:jsonString forKey:@"songs"];
[request setDelegate:self];
[request startAsynchronous];
The key was to convert the info to NSData
, then to a JSON String which I sent to my server, not just sending the raw NSData
.Thanks everyone for the help!
Convert result_array() to JSON object
Try to return the query result
not result_array
model function
function getRecords(){
$sql = 'SELECT * FROM table';
$query = $this->db->query($sql);
return $query->result();
}
Convert to json$object = getRecords();
$json_obj = json_encode($object);
How do I receive a JSON object from PHP backend and convert to JavaScript array for frontend
ok so with some of the answers and a little more experimenting this is what I have and its a start to the rest of the solution
I changed this line
this.setState({data:response})
to this.setState({data:response.data})
and changed the render to this render() {
const {data} = this.state
let result = [];
Object.values(data).map(num =>
result.push(num)
);
return (
<div>
{result.map(tile =>
`<div><img src='${tile.image}'/></div>`
)}
</div>
)
}
Representing null in JSON
Let's evaluate the parsing of each:
http://jsfiddle.net/brandonscript/Y2dGv/
var json1 = '{}';
var json2 = '{"myCount": null}';
var json3 = '{"myCount": 0}';
var json4 = '{"myString": ""}';
var json5 = '{"myString": "null"}';
var json6 = '{"myArray": []}';
console.log(JSON.parse(json1)); // {}
console.log(JSON.parse(json2)); // {myCount: null}
console.log(JSON.parse(json3)); // {myCount: 0}
console.log(JSON.parse(json4)); // {myString: ""}
console.log(JSON.parse(json5)); // {myString: "null"}
console.log(JSON.parse(json6)); // {myArray: []}
The tl;dr here:
The fragment in the json2 variable is the way the JSON spec indicates
null
should be represented. But as always, it depends on what you're doing -- sometimes the "right" way to do it doesn't always work for your situation. Use your judgement and make an informed decision.
JSON1
{}
This returns an empty object. There is no data there, and it's only going to tell you that whatever key you're looking for (be it myCount
or something else) is of type undefined
.
JSON2
{"myCount": null}
In this case, myCount
is actually defined, albeit its value is null
. This is not the same as both "not undefined
and not null
", and if you were testing for one condition or the other, this might succeed whereas JSON1 would fail.
This is the definitive way to represent null
per the JSON spec.
JSON3
{"myCount": 0}
In this case, myCount is 0. That's not the same as null
, and it's not the same as false
. If your conditional statement evaluates myCount > 0
, then this might be worthwhile to have. Moreover, if you're running calculations based on the value here, 0 could be useful. If you're trying to test for null
however, this is actually not going to work at all.
JSON4
{"myString": ""}
In this case, you're getting an empty string. Again, as with JSON2, it's defined, but it's empty. You could test for if (obj.myString == "")
but you could not test for null
or undefined
.
JSON5
{"myString": "null"}
This is probably going to get you in trouble, because you're setting the string value to null; in this case, obj.myString == "null"
however it is not == null
.
JSON6
{"myArray": []}
This will tell you that your array myArray
exists, but it's empty. This is useful if you're trying to perform a count or evaluation on myArray
. For instance, say you wanted to evaluate the number of photos a user posted - you could do myArray.length
and it would return 0
: defined, but no photos posted.
Pretty-Printing JSON with PHP
PHP 5.4 offers the JSON_PRETTY_PRINT
option for use with the json_encode()
call.
https://php.net/manual/en/function.json-encode.php
<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);
Convert JSON string to an array in JavaScript
One option is to use eval
:
var arr = eval('(' + json_text + ')');
The above is easiest and most widely supported way of doing this, but you should only use eval
if you trust the source as it will execute any JavaScript code. Some browsers have a native JSON parser in which case you can do the following:
var arr = JSON.parse(json_text);
Third-party libraries such as jQuery can also provide functions for dealing with JSON. In jQuery, you can do the following:var arr = jQuery.parseJSON(json_text);
The bottom two methods (which use a parser) are preferred as they provide a level of protection. Binary Data in JSON String. Something better than Base64
There are 94 Unicode characters which can be represented as one byte according to the JSON spec (if your JSON is transmitted as UTF-8). With that in mind, I think the best you can do space-wise is base85 which represents four bytes as five characters. However, this is only a 7% improvement over base64, it's more expensive to compute, and implementations are less common than for base64 so it's probably not a win.
You could also simply map every input byte to the corresponding character in U+0000-U+00FF, then do the minimum encoding required by the JSON standard to pass those characters; the advantage here is that the required decoding is nil beyond builtin functions, but the space efficiency is bad -- a 105% expansion (if all input bytes are equally likely) vs. 25% for base85 or 33% for base64.
Final verdict: base64 wins, in my opinion, on the grounds that it's common, easy, and not bad enough to warrant replacement.
See also: Base91 and Base122
Related Topics
How to Call Curl_Setopt with Curlopt_Httpheader Multiple Times to Set Multiple Headers
Number in the Top-Level Domain
Php: $_Server Variables: $_Server['Http_Host'] VS $_Server['Server_Name']
How to Refresh Select2 Dropdown Menu After Ajax Loading Different Content
Resource Interpreted as Image But Transferred with Mime Type Text/HTML - Magento
Jquery Ajax Form Data Serialize Using PHP
How to Keep a PHP Session Active Even If the Browser Is Closed
Doctrine 2 Lifecyclecallbacks with Abstract Base Class Are Not Called
Force Logout Users If Users Are Inactive for a Certain Period of Time
Mysqli_Store_Result() VS. MySQLi_Use_Result()
PHP Class: Global Variable as Property in Class
How to Get the Absolute Path to the Public_HTML Folder
How to Build a Condition Based Query in Laravel
How to Select Year and Month from the Created_At Attributes of Database Table in Laravel 5.1
Programmatically Create Image from Web-Page or a Single Div
PHP Datetime::Createfromformat Doesn't Parse Iso 8601 Date Time