how to parse backslash json structure using jquery parse? - javascript

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}

Related

Javascript to fetch json from unordered data

I have below input code inside script code which comes like a string
The output should be below as a JSON object and extract flags and preference object. Need a solution using regex or any other way
flags = { "onFlag" : true, "offFlag : false }
Preference = { "onPreference" : true, "offPreference : false }
You can use regex to extract data inside the script tag and then parse content in javascript to generate JSON.
const regex = /<script[^>]+>(.*?)<\/script>/gs;
const str = `<script type="text/javascript">
window.__getRoute__=function() {
console.log('hi');
}
window.__LOADED_STATE__ = {
"context": {
"flags": {"onFlag": true, "offFlag": false},
"Preference": {"onPreference": true, "offPreference": false}
}
}
</script>`;
const m = regex.exec(str);
const json = new Function('var window={}; ' + m[1] + ' return window.__LOADED_STATE__')();
console.log(json.context.flags);
console.log(json.context.Preference);

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;
}

Can't access data inside an object - rookie Javascript question

This is a rookie question about accessing an array inside an object and converting it to JSON.
Error I am getting when running the GET method below:
Cannot read property 'VehicleList' of undefined
How to fix this?
let get = https.get(
{
hostname: 'xyz.com',
path: path_get_all_vehicles //this variable is known and passed into path
},
(getRes) => {
console.log(`executing getRes...`);
var reply = "";
getRes.on("data", (chunk) => {
(reply += chunk);
}
);
getRes.on("end", () => {
gotCars(JSON.parse.stringify(reply.Response.VehicleList)); //ERROR
}
);
}
);
Data format is shown below and the idea is to access the VehicleList array, convert it to JSON and then pass it, after parsing, to function gotCars
{
"ResponseStatus": 1,
"Response": {
"VehicleList": [
{
"ID": AAA,
"BrandID": 89,
"ModelID": 980,
"VersionID": 11289
},
{
"ID": BBB,
"BrandID": 89,
"ModelID": 980,
"VersionID": 8338
},
],
"VehicleCount": 17866
}
}
The expression JSON.parse.stringify(reply.Response.VehicleList) is invalid for a couple reasons:
The global JSON.parse does not have a property named stringify (undefined)
undefined cannot be called
The global String.prototype (reply is a string) does not have a property named Response (undefined)
undefined cannot be indexed
I assume you are trying to parse reply as JSON and then get the VehicleList array from the result, try this code:
let get = https.get(
{
hostname: "xyz.com",
path: path_get_all_vehicles // this variable is known and passed into path
},
(getRes) => {
console.log(`executing getRes...`);
var reply = "";
getRes.on("data", (chunk) => {
reply += chunk;
});
getRes.on("end", () => {
gotCars(JSON.parse(reply).Response.VehicleList);
});
}
);
You first need to parse reply, that will create the object. Then you can access its properties.
getRes.on("end", () => {
const obj = JSON.parse(reply);
gotCars(obj.Response.VehicleList);
});

How to convert objects of array in to XML in Javascript

I have a data nested data structure or JSON, how can I convert that into an XML structure in Javascript.
[
{"loanId" : "LA00123", "MemberId" : "MI00123"},
{"loanId" : "LA001234", "MemberId" : "MI001234"}
]
Excepted result:
<result>
<loanID>LA00123</loanID>
<MemberId>MI00123</MemberId>
</result>
<result>
<loanID>LA001234</loanID>
<MemberId>MI001234</MemberId>
</result>
Simply by an iteration you can preapre the XML element first and the join by empty character.
Here Array.prototype.map() is used to make an iteration over the array and Array.prototype.join() is used to concatenate the prepared XML element to final result.
const data = [{"loanId" : "LA00123", "MemberId" : "MI00123"},{"loanId" : "LA001234", "MemberId" : "MI001234"}]
const result = data.map(obj => `<result><loanID>${obj.loanId}</loanID><MemberId>${obj.MemberId}</MemberId></result>`).join('')
console.log(result)
If you're converting data into XML as a string, you could perform reduce on the array:
let obj = [{
"loanId": "LA00123",
"MemberId": "MI00123"
},
{
"loanId": "LA001234",
"MemberId": "MI001234"
}
];
const toXml = (data) => {
return data.reduce((result, el) => {
return result + `<result><loadId>"${el.loanId}"</loadID><MemberId>${el.MemberId}</MemberId></result>\n`
}, '')
}
console.log(toXml(obj));
Creating XML object (overkill):
let obj = [{
"loanId": "LA00123",
"MemberId": "MI00123"
},
{
"loanId": "LA001234",
"MemberId": "MI001234"
}
];
let doc = document.implementation.createDocument(null, "myXML");
obj.forEach(a => {
let result = doc.createElement("result");
Object.entries(a).forEach(b => {
let node = doc.createElement(b[0]);
node.append(doc.createTextNode(b[1]));
result.append(node);
});
doc.documentElement.append(result);
});
console.log(new Array(...doc.documentElement.children).reduce((a, b) => a + new XMLSerializer().serializeToString(b), ''));

Parsing JSON object

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 });

Categories