Parsing JSON object - javascript

How I can parse 2 JSON objects? e.g
AJAX return just one Object appear's correctly.
Object {32 : "Joseph"}
But, when return more than 2 objects, I've got this:
ResponseText: "{"users":{"32":"Jospeh"}}{"users":{"48":"Jospeh K."}}"
I already trieD to parse with JSON.parse but returns an error: "Uncaught SyntaxError: Unexpected token {"
So, How I can parse to return something like this:?
Object {32 : "Joseph"}
Object {48 : "Joseph K"}
Instead of "responseText"
Considerations:
If returns just ONE object, appears correctly in console(example);
If returns more than TWO objects, appears responseText;
AJAX dataType: JSON
I'll be very grateful if someone can help with this. =D
PHP:
public function get_error_message()
{
$message = "";
foreach ($this->errors as $value) {
if ($value instanceof UsersError) {
$message.= json_encode(array('errors' => array($value->getCode() => $value->getMessage())));
}
}
return $message;
}

The problem is in your PHP code. You can't simply concatenate JSON and think that it will be valid.
Instead of
$message = "";
foreach ($this->errors as $value) {
if ($value instanceof UsersError) {
$message.= json_encode(array('errors' => array($value->getCode() => $value->getMessage())));
}
}
you should generate a proper PHP object, and then encode it to JSON once.
For example, in your case, it can be an array:
$errorsArray = array();
foreach ($this->errors as $value) {
if ($value instanceof UsersError) {
$errorsArray[] = array($value->getCode() => $value->getMessage());
}
}
echo json_encode(array('errors' => $errorsArray));
Then, a result will be the following no matter how many objects it returns - none,
{
"errors": []
}
only one or
{
"errors": [
{"32": "Joseph"}
]
}
many
{
"errors": [
{"32": "Joseph"},
{"48": "Joseph K."}
]
}
In JavaScript you will be able to do:
$.ajax({}).done(function(data) {
console.log(data.errors.length);
});
You can generate another JSON response which will be more convenient to work with in JavaScript. It's up to your requirements and fantasy.
For example, I would do a single associated array:
PHP:
$errorsArray = array();
foreach ($this->errors as $value) {
if ($value instanceof UsersError) {
$errorsArray[$value->getCode()] = $value->getMessage();
}
}
echo json_encode(array('errors' => $errorsArray));
JSON:
{
"errors": {
"32": "Joseph",
"48": "Joseph K."
}
}

That's not a valid JSON object. It is 2 JSON object in string representation concatenated together, which as far as I know is not valid. If you can't change the back-end, and you have to process this and can guarantee it is always 2 JSON object concatenated together, then you'll have to use string parsing to split them before sending them into JSON.parse(...) individually to get 2 JSON objects back.

this is not really standard way and your json is not valid:
but try this
str_data = "{'users':{'32':'Jospeh'}}{'users':{'48':'Jospeh K.'}}";
str_data = str_data .replace("}{", "}}{{");
items = str_data .split("}{");
object_items = [];
for(i =0; i < items.length; i++){ object_items[i] = JSON.parse(items[i]); }

Your JSON is invalid, try push users into an array.
var obj = {
"users": [
{
"name": "Jospeh",
"age": 32
},
{
"name": "Joseph K",
"age": 48
}
]
}
And for new users just push...
obj.users.push({ "name": "Neil A.", "age": 72 });

Related

How to convert a JavaScript object to a PHP array and get the raw string?

In my application I need to convert a JavaScript Object to a raw PHP array returned as text string. I would do this calling an API. I don't need to manupulate the array. In my JavaScript application, I just need the plain PHP object string as showed below. (Like using this: https://wtools.io/convert-js-object-to-php-array)
The JavaScript object is:
{
"name":"A Name",
"_typography": {
"color": {
"hex":"#2196f3"
},
"text-transform":"uppercase",
"font-weight":"600"
}
}
How I send the JavaScript Object to the PHP function
JSON.stringify(jsObject);
What I need as string output:
[
"name" => "A Name",
"_typography" => [
"color" => [
"hex" => "#2196f3"
],
"text-transform" => "uppercase",
"font-weight" =>"600"
]
]
What I tried is to first json_decode the JavaScript object to a PHP object and then try to return it as a plain string back. But no chance. Either I get a Js Object back or something else entirely. I have no more ideas.
My try
function convert_js_object_to_php(WP_REST_Request $request) {
// Getting the JS object
$object = $request->get_header('js_object');
// Decoding it to a PHP object
$output = json_decode($object);
if ($output) {
return strval($output);
// return $output (Here I also get the JavaScript object again)
// return implode($output) (I don't get the plain PHP array)
}
return false;
}
Do you have any idea?
Is this what you are trying to achieve?
$incoming is the jsonString coming from the javascript code
$incoming = '{
"name":"A Name",
"_typography": {
"color": {
"hex":"#2196f3"
},
"text-transform":"uppercase",
"font-weight":"600"
}
}';
$a = json_decode($incoming, true);
echo var_export($a);
RESULT
array (
'name' => 'A Name',
'_typography' =>
array (
'color' =>
array (
'hex' => '#2196f3',
),
'text-transform' => 'uppercase',
'font-weight' => '600',
),
)
Only changes are that you should add true to json_decode and use var_export to get the php array string. If you wanted to get square bracket you could write some custom string generator code.
function convert_js_object_to_php() {
// Getting the JS object
$object = $request->get_header('js_object');
// Decoding it to a PHP object
$output = json_decode($object, true);
if ($output) {
return var_export($output, true);
}
return false;
}

Is it possible to return json_encode() but as an array and not an object, so I can use `.filter()` or `.forEach()` methods easily

I just want to make sure there is no such thing... because I cannot find anything mentioning this:
Currently, when I use json_encode($array), I get a json object that look like this:
{
"1": {"user_id":1,"test":"","user_name":"potato0","isok":"true"},
"2":{"user_id":2,"test":"","user_name":"potato1","isok":" true"},
"3":{"user_id":3,"test":"","user_name":"potato2","isok":" true"},
"4":{"user_id":4,"test":"","user_name":"potato3","isok":"locationd"}
}
and I would like to run the .filter()/.forEach() methods.
but they wont run on objects ({...}) and will run on arrays ([...]).
Edit: It seems that it's not sure what I am getting so this is a real var_dump and json_encode() example:
var_dump($array);
array (size=2)
'status' => boolean true
'data' =>
array (size=3)
'fruits' =>
array (size=9)
'fruit_id' => int 246
'fruit_name' => string 'banana' (length=15)
'vegtables' =>
array (size=9)
'veg_id' => int 253
'fruit_name' => string 'potato' (length=20)
echo json_encode(['status' => true, 'data' => $fruits]);
{
"status":true,
"data":{
"fruits":{
"fruit_id":246,
"fruit_name":"banana"
},
"vegtables":{
"veg_id":253,
"veg_name":"potato"
}
}
}
the json returned is defined as an "Object" (checked using typeof)
** I'm not willing to turn my object to an array on the js side, I aware about this "trick" and I prefer to fetch a json array from php as an array, please focus on my question **
You need to change the main object to an Array. I think below code is what you're looking for.
Your Input :
var data = {
"1": {"user_id":1,"test":"","user_name":"potato0","isok":"true"},
"2":{"user_id":2,"test":"","user_name":"potato1","isok":" true"},
"3":{"user_id":3,"test":"","user_name":"potato2","isok":" true"},
"4":{"user_id":4,"test":"","user_name":"potato3","isok":"locationd"}
};
Convert Object to Array
var result = Object.keys(data).map(function(key) {
return data[key];
});
Now you can use Filter for the converted array
var filtered = result.filter(row => { return row.user_id > 1; });
And Filtered Result is:
[{
"user_id": 2,
"test": "",
"user_name": "potato1",
"isok": " true"
},{
"user_id": 3,
"test": "",
"user_name": "potato2",
"isok": " true"
},{
"user_id": 4,
"test": "",
"user_name": "potato3",
"isok": "locationd"
}]
Hope this is what you're looking for and here is working demo link : https://playcode.io/282703?tabs=console&script.js&output

How to parse all JSON strings in a JavaScript object

I have 1 JavaScript object like this:
result = {
"status": "success",
"message": "Get successful!",
"data": {
"name":"Hello world",
"school": {
"name":"LHP",
"address":"HCM"
},
"class": "[{\"text\":\"Math\",\"code\":\"math124\"},{\"text\":\"Libra\",\"code\":\"libra124\"}]",
"student": "{\"time_range\":{\"type\":\"select\",\"text\":\"Today\",\"value\":[{\"code\":\"in_today\",\"text\":\"In Today\"}]}}"
}
}
So I have to parse class and student separately:
result.data.class = JSON.parse(result.data.class);
result.data.student = JSON.parse(result.data.student);
Is there other way to parse the whole result variable or make this step shorter/better?
Thanks
You could loop through the data property's children and parse them.
for (var i = 0; i < Object.keys(result.data).length; i++) {
try {
result.data[Object.keys(result.data)[i]] = JSON.parse(result.data[Object.keys(result.data)[i]]);
} catch (error) {} // it's already JSON
}
But I'd only do that if you're sure you'll only ever have to deal with stringified JSON in the data property of your object.

how to parse backslash json structure using jquery parse?

This is my code. I have used jquery parse. Can you Please help me? How to parse this?
var jsondata= {
"forms": [
"{\"lat\":11.913859799999999,\"lng\":79.8144722}",
"{\"lat\":11.913859799999999,\"lng\":79.8144722}"
]
}
var a=$.parseJSON(jsondata);
alert(a.forms[0].lat); // not working show "undefined"
error:
Uncaught SyntaxError: Unexpected token ,
You have to parse the forms[0] element to convert it to a real object:
var jsondata= {
"forms": [
"{\"lat\":11.913859799999999,\"lng\":79.8144722}",
"{\"lat\":11.913859799999999,\"lng\":79.8144722}"
]
}
var result = document.querySelector('pre');
result.textContent = JSON.parse(jsondata.forms[0]).lat;
// ^ parse here
// parse all elements of jsondata.forms:
// first: convert the elements of jsondata.forms to objects
jsondata.forms = jsondata.forms.map(function (v) { return JSON.parse(v); });
// now the jsondata.forms elements are objects
result.textContent += '\n\nThe converted jsondata.forms Array\n' +
JSON.stringify(jsondata.forms, null, ' ') +
'\n\nso: jsondata.forms[1].lng = ' + jsondata.forms[1].lng;
<pre></pre>
JSON is not JavaScript! It is a data serialization format.
var jsondata =
"{ \"forms\": ["
+ "{\"lat\":11.913859799999999,\"lng\":79.8144722} , "
+ "{\"lat\":11.913859799999999,\"lng\":79.8144722} ] }"
var a = JSON.parse(jsondata)
no need for jQuery -- the JavaScript language provides native JSON.parse and JSON.stringify
JSON data must be one long, single string that is passed to parse
JSON keys have to be quoted
I think the backend is generating a wrong response to your application
Sample like this lets say i have an array of
$data['default'] = array(
array(
'email' => 'sample#gmail.com',
'username' => 'username1'
),
array(
'email' => 'sample#yahoo.com',
'username' => 'username2'
),
array(
'email' => 'sample#hot.com',
'username' => 'username3'
)
);
$data['title'] = 'Sample';
and use
echo json_encode(json_encode($data));die();
would result to a data like this
"{\"default\":[{\"email\":\"sample#gmail.com\",\"username\":\"username1\"},{\"email\":\"sample#yahoo.com\",\"username\":\"username2\"},{\"email\":\"sample#hot.com\",\"username\":\"username3\"}],\"title\":\"Sample\"}"
but if use only
echo json_encode($data);die();
It would create a valid json data
{
"default": [
{
"email": "sample#gmail.com",
"username": "username1"
},
{
"email": "sample#yahoo.com",
"username": "username2"
},
{
"email": "sample#hot.com",
"username": "username3"
}
],
"title": "Sample"
}
Using your data
var jsondata= {
"forms": [
"{\"lat\":11.913859799999999,\"lng\":79.8144722}",
"{\"lat\":11.913859799999999,\"lng\":79.8144722}"
]
};
and using some jQuery code:
$.each(jsondata.forms, function(i, me){
console.log(JSON.parse(me));
});
using navite javascript
for (var i = 0; i < jsondata.forms.length; i++) {
console.log(JSON.parse(jsondata.forms[i]));
}
returns
{lat: 11.913859799999999, lng: 79.8144722}
{lat: 11.913859799999999, lng: 79.8144722}

Storing JSON data in database: object could not be converted to string error

In a nut shell, I have my data in Javascript:
JSONdata = {
name: form.name.value,
address1: form.custa.value,
address2: form.custa2.value,
postcode: form.custpc.value,
order: fullorder,
cost: document.getElementById('total')
}
fullorder is an array of products to be ordered. :
[{"idnum":"2","cost":232,"quantity":"1"},{"idnum":"1","cost":2342,"quantity":"3"}]
I have an XJAX which stringifies this data as seen below:
{"name":"j","address1":"jh","address2":"jhj","postcode":"h","order":[{"idnum":"2","cost":232,"quantity":"1"},{"idnum":"1","cost":2342,"quantity":"3"}],"cost":{}}
In PHP it's given as an array:
Array
(
[0] => stdClass Object
(
[idnum] => 2
[cost] => 232
[quantity] => 1
)
[1] => stdClass Object
(
[idnum] => 1
[cost] => 2342
[quantity] => 3
)
)
My question is how to store this in an database?
I've tried serialize and json_encode but both give me a:
"Object of class stdClass could not be converted to string".
Any help would be greatly appreciated!
-> Don't worry about querying the database and the JSON battle.
I will be getting all data out at once so it's not an issue :)
EDIT: Thanks for the replies guys, I give you some info about how it works:
So when I send the JSON to my PHP, I have a script which extracts all the data out like so:
$intel = extractdata();
function extractdata() {
if (isset($_REQUEST['data'])){
$jsonDump = json_decode($_REQUEST['data']);
foreach($jsonDump as $key => $value) {
$obj[$key] = $value;
}
return $obj;
}
So this gives me
$intel['name'] = // form.name.value variable
$intel['address1'] = // form.name.value variable
And $intel['order'] gives me the PHP array seen above. I want to store all this in to a database in the columns: Customername, address1, address2, postcode, order, cost
I thought by just $neworder = json_encode($intel['order']) would allow me to store it in a database but it still throws the convertion error.
Thanks
So basically you have an array that contains an object like this:
$o = array((Object)array(array("idnum"=>2, "cost"=>232, "quantity"=>1), array("idnum"=>1, "cost"=>2342, "quantity"=>3)));
Echoing this with json_encode() will return a json string:
echo json_encode($o);
and the result will be
[
{
"0": {
"idnum": 2,
"cost": 232,
"quantity": 1
},
"1": {
"idnum": 1,
"cost": 2342,
"quantity": 3
}
}
]
isn't this working for you? Also are you using any framework or just pure php?
If you have this:
$jsonDump = json_decode($_REQUEST['data']);
I believe you dont need this:
foreach($jsonDump as $key => $value) {
$obj[$key] = $value;
}
moreover, you don't initiate $obj (should be $obj = null at the beggining of the function or sth.).
What you need is json_encode((array) $obj); to convert the object to a simple array before stringifying, this should solve your problem. You can also implement a _toSting($obj) function like:
$str = '{';
foreach($obj as $key => $value) {
$str .= '"'.$key.'":"'.$value.'"';
$str .= ',';
}
$str = trim(',',$str).'}';

Categories