1[[23[]]
I understand that '[' denotes a JOSNArray and '{' denotes a JSONObject. However as my result starts with [ is the entire data piece now an array even if { comes before the actual string?
And if parsing in android, should I be parsing for array or object?
My PHP script:
It's an array contsining single object. The string delimits name of the first item of the first object.
As stated by Zbynek Vyskovsky its an array with single object so to get the data you can use
JSONArray jsonArray=new JSONArray(<your json object>);
JSONObject jsonObject = jsonArray.get(0);
String date = jsonObject.getString("Date");
String temp = jsonObject.getString("Temp");
The best way to determine this is format first .
paste your response in this site http://json.parser.online.fr/
there you will see
1)red square brackets -represent an array.
2)blue curly brackets represents an object.
in short you have an array containing single object.
Your Json is an array which contains only one Json object.I will show actually how it works with JSon Array and JsonObject.
For example I have a JSON Array :
[{
"name": "abc",
"description": "ABC server",
"state": "online"
},
{
"name": "xyz",
"description": "XYZ client",
"state": "online"
},
{
"name": "mnp",
"description": "MNP server",
"state": "online"
}]
So The above array actually contains 3 Json objects like [{Obj1},{Obj2},{Obj3}].
When we try to get any of the value for a key then first we need to store the JSon Array and then after we need to get the exact Json object by passing index e.g: jsonObject obj = JsonArray.get(0).
Soon after you pass the key to the Json object in get() method, you will get your key. e.g: String s = obj.get("state").
Related
In my database I have POSTed following JSON with REST API:
{
"author": "Someone",
"hero_name": "Iron Man",
"hero_desc": ["Iron", "Man"],
}
Now in database Table, the entry says only Array for the hero_desc.
I cannot figure out how to get the actual items in that array.. for example to fetch Iron from hero_desc.
Here is how it gets returned with GET request:
{
"id": "11",
"user_id": "1",
"author": "Someone",
"hero_name": "Iron Man",
"hero_desc": "Array",
}
I am quite new to PHP so I am worried that I would need to mess up my whole app architecture to get this to work. I though PHP can handle fetching arrays by default if it sees it's an JSON Array.
use json_decode(); function for change json to array
$json_to_array = json_decode($your_json_variable_name);
You could change array data to JSON with json_encode In one hand you have an array without the key that code makes a number key for that in another hand if have an array with the key you can get that inside JSON with that key.
$content ='your content or your array data';
header('Content-Type: application/json; charset=utf8');
echo json_encode($content);
from angularjs 2 my application getting below json value but i am not able to convert this json value to an array.
$response = '{username: "mosh", time: "2017-01-22T11:28:54.422Z"}';
$json_arrya = json_decode($response,true);
var_dump($json_arrya);
current output: NULL
expected output as an array
Try the json below
{
"username": "mosh",
"time": "2017-01-22T11:28:54.422Z"
}
to see if that works.
Also, this is a json object not an array so you might have to pass it as an array from your angular service like
[{ "username": "mosh", "time": "2017-01-22T11:28:54.422Z"}]
I'm attempting to do something I've done many times before (access objects in a JSON file with PHP) and for some reason json_decode is only returning the last item in the JSON array. Here's the JSON:
{
"person": {
"lname": "smith",
"fname": "bob"
},
"person": {
"lname": "jones",
"fname": "jane"
}
}
And the PHP:
<?php
//access and dump
$json = file_get_contents('people.json');
$filey = json_decode($json, true);
var_dump($filey);
?>
The result is only the last item in the array:
array (size=1)
'person' =>
array (size=2)
'lname' => string 'jones' (length=5)
'fname' => string 'jane' (length=4)
Using json_last_error returns no errors and I'm valid according to jsonlint. I'm also not finding any console errors when I load the page.
I'm totally stumped and can't see anything different from the times I've done this before - can anyone identify what I'm missing here?
That's because your json object names "person" within json array are similar so json decode will override the values with latest.
Consider something like
{
"person1": {
"lname": "smith",
"fname": "bob"
},
"person2": {
"lname": "jones",
"fname": "jane"
}
}
and your code will work fine.
Marcatectura, I know you've already accepted the answer that suggests using different object keys but I thought you should know. If you want an array in PHP, You don't even need object names. The following JSON will do:
[
{
"lname": "Dawes",
"fname": "April"
},
{
"lname": "Colin",
"fname": "Dick"
}
]
A trick I use when I'm designing my JSON is to build a sample PHP array in the shape I want json_decode to give me, encode that array and output the result to screen. So what I posted above is the result of:
$arr = [
['lname'=>'Dawes','fname'=>'April'],['lname'=>'Colin','fname'=>'Dick'],
];
$json = json_encode($arr);
echo $json;
Since I built a JSON by encoding an array having the shape I want, I can be confident that even as my data change, json_decode($json,true) will give me the array shape I expect.
Happy coding.
When you use json_decode(true), your json is now an array.
You cannot have two array keys that are the same, in this case "person".
If you still want to use json_decode(true), then change "person" to "person1" or so.
Try both var_dump($filey) and var_dump($json), you will see what I'm talking about.
I read several posts on here and have been unable to find success in resolving the problem I am having.
I am trying to figure out how to get the NAME field from the UploadImage array.
I have the following JSON being passed to me from a Webhook.
{
"$version":5,
"Entry":{
"Number":"11",
"Order":null,
"Origin":
{
"City":"Portland",
"CountryCode":"US",
}
,
"Message":"the message",
"UploadImage":[
{
"ContentType":"image/png",
"Id":"F-lMbiCYdwiYS8ppkQS4gsyE",
"Name":"Screen.png",
"Size":55907
}
],
"Subject":"here is the subject"
}
I have no problem grabbing the value of Subject or Message, but I cannot figure out how to grab the NAME within UploadImage.
$contact = json_decode($json);
$subject=$contact->{'Subject'};
When I do
$uploadimage=$contact->{'UploadImage'};
it just writes out ARRAY.
I can do
echo $contact->{'Entry'}->{'Number'};
and it works, so it has to be something with the bracket being there before the curly bracket. I know this has to be something simple that I am missing.
Any help is GREATLY appreciated.
$uploadimage=$contact->{'UploadImage'}[0]->{'Name'};
Firstly try
$contact = json_decode($json, true);
Adding the second argument returns an array instead of an object which will make things easier. Objects with numerical keys are troublesome... Now you can,
print_r($contact);
to see exactly what you've got. I imagine that
echo $contact['UploadImage'][0]['Name'];
Will get you what you're looking for.
Notice that UploadImage contains an array of objects (or an array of arrays after conversion).
another solution is:
$contact = json_decode($text);
$name = '';
foreach($contact->UploadImage as $k=>$v){
foreach($v as $k2=>$v2){
echo $k2.' - '.$v2.'<br />';
if($k2=='Name'){ $name = $v2;}
}
};
var_dump($name);
//response
ContentType - image/png
Id - F-lMbiCYdwiYS8ppkQS4gsyE
Name - Screen.png
Size - 55907
//name
string 'Screen.png' (length=10)
Have you try to use like below:
$uploadimage=$contact->UploadImage[0]->Name;
In JSON the square braces [] mark an array section and the curly braces {} mark an object. In your JSON string UploadImage is an array, which contains a single object.
Try changing your JSON as follows:
{
"$version": 5,
"Entry": {
"Number": "11",
"Order": null,
"Origin": {
"City": "Portland",
"CountryCode": "US"
},
"Message": "the message",
"UploadImage": {
"ContentType": "image/png",
"Id": "F-lMbiCYdwiYS8ppkQS4gsyE",
"Name": "Screen.png",
"Size": 55907
},
"Subject": "here is the subject"
}
}
I wonder how to parse a json array without values
Json: {"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}
How can i get the value of email in a foreach loop?
What i mean with "without value" is: there is an array called email and name... How can i get the value for "email" that currently says NOT_UNIQUE?
In your current example, your JSON string is malformed. I dont know if thats a typo on your part while creating your question. Assuming the JSON string is okay in your code, a simple json_decode() will do just fine. Consider this example:
$json_string = '{ "Json": { "status": "FAILED", "errors": { "email": [ "NOT_UNIQUE" ], "name": [ "TOO_SHORT" ] } }}';
$data = json_decode($json_string, true);
echo $data['Json']['errors']['email'][0]; // NOT UNIQUE
use json_decode, json_decode($str, true) will return it as an assosiative array whereas json_decode($str, false) will return objects.
json_decode("{"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}", true)['errors']['email']
should get the email for you.