Convert JSON object to array? - json

I have this on my console on firebug,
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...}, Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
it is data from the server side. Now, how would I convert this into array such that this data can be used on another file. I tried JSON.parse and jQuery.parseJSON but both did not work.

That isn't JSON it's a Javascript array of objects, not a string. My guess is that you've received this from a jQuery ajax call and you had the dataType : 'json' set so that jQuery has automatically parsed the JSON into this array.
To send it to a PHP script you can convert it back to JSON using:
var myString = JSON.stringify(data);
and then fire off an ajax call to the PHP script with that as the POST data:
var myString = JSON.stringify(data);
$.post('page.php', { data : myString }, function(){
console.log( "sent" );
});
In PHP you can decode it using:
$data = json_decode($_POST['data']); // <-- or whatever your post variable is named
foreach($data as $obj)
{
echo $obj->fa_id;
}

if you want to get an php array use this
http://php.net/manual/en/function.json-decode.php

The string you provided is not valid JSON.
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...},
Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
In particular, the "Object" and "more..." strings cannot be interpreted by a JSON parser.
Assuming the object you are inspecting is a variable named foo:
console.log(JSON.stringify(foo));
Should print a valid JSON representation of your object to the Javascript console.

Related

Dart/Flutter : Avoid Method parsing in Map , when converting to JSON?

In Dart / Flutter , when converting a map (which contains a Closure method) to json using jsonEncode , I getting following error :
Converting object to an encodable object failed: Closure: () => dynamic
The Map having :
orderedMap1["fooddelete"] = () => deleteItemFunction(
singleitem["orderId"], singleitem["id"], singleitem["shopId"]);
If commented above line , then jsonEncode works , else throwing above error .
How to instruct the jsonEncode to skip the closures when parsing Map to Json ?
It seems highly questionable to store closures in the same Map that you want to encode to JSON, but if you must, you can encode a filtered copy of it instead:
var encoded = jsonEncode({
for (var entry in orderedMap1.entries)
if (entry.value is! Function) entry.key: entry.value,
});
I suppose you alternatively could use jsonEncode's toEncodable parameter to convert closures to something else, although I'm not sure what good that would do you since there's nothing the recipient could do with it. The following will replace closures with null:
var encoded = jsonEncode(orderedMap, toEncodable: (value) {
if (value is Function) {
return null;
}
throw UnsupportedError('Cannot convert to JSON: $value');
});
option1: remove "fooddelete" key using orderedMap1.remove("fooddelete") and then parse it.
option2: put your Closure inside the double quotation. so you can save it as String.

have to JSON.parse twice to extract json object from stringified QR Code

I have some JSON
{
id: "abcd",
type: "receive"
}
which I stringified and generated a QR code using some online QR code maker. In my react native app, I am using react-native-qrcode-scanner to scan this qr code which calls an onSuccess(qrCode: Event) function.
I've set up the function as follows:
function onSuccess(qrCode: Event) {
console.log(qrCode.data);
const parsedData = JSON.parse(qrCode.data);
console.log(parsedData);
console.log(typeof parsedData);
console.log(parsedData.id);
const parsedData2 = JSON.parse(parsedData);
console.log(parsedData2.id);
navigation.navigate('Home');
}
This gives the following output
"{\"type\":\"receive\",\"id\":\"abcd\"}"
{"type":"receive","id":"abcd"}
string
undefined
abcd
So basically, qrCode.data is a string which is expected. parsedData outputs like an object, but has typeof string. Accessing properties on parsedData gives undefined - which makes sense if it's a string. When I parse it a second time into parsedData2 that is an object and I can access properties on it.
My confusion is, why is it not just parsing it the first time? Why do I have to do it twice?

Angular 6: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse with valid JSON

I am not sure whether my function is wrong, which should send data to the server, or the function on the server is wrong.
I looked up similar questions but the solution I adopted to my problem did not work.
My function looks like this:
postData(number){
let array = JSON.stringify(this.locArr);
return this.http.post<any>(this.url, array)
.subscribe(),
error => console.log("Error: ", error)
}
JSON which is send:
[
{
"id":222,
"name":"Lars",
"sLA":37
},
{
"id":223,
"name":"Sim",
"sLA":12
}
]
All parameters like token etc. are received by the server function but the array I wrote above is null, although it is valid json.
I wonder why this error is occuring.
Any advice is appreciated
The local array will be converted into JSON automatically by Angular, you need not stringify or parse it.
postData(number){
this.http.post<any>(this.url, this.locArr)
.subscribe((data)=>{
//code after receiving data from server
},
error => console.log("Error: ", error))
}
I believe you are using httpClientModule so then there is no need of tyou need't JSON.stringify remove this step JSON.stringify(this.locArr);
Also you need to send it as json object {} not json array []
postData($locArr){ // pass the array to the service function
let data = { data : $locArr}; // note that you have to post it as json object {} not []
return this.http.post<any>(this.url,data);
}

How to read a JSON object with a full-stop in the name using POSTMAN?

I have a problem trying to check a JSON value in the response body using POSTMAN because the JSON object name has a full-stop in it
Usually a JSON response body would be something like this:
{
"restapi": "Beta",
"logLevel": "INFO"
}
So normally we can do a test on the JSON value like this using POSTMAN:
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.restapi).to.eql(Beta);
});
But the problem I'm having now is that the JSON object name has a full stop like this
{
"restapi.name": "Beta",
"logLevel.sleep": "INFO"
}
So if I try to do read the object like this, it will come out with an error
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.restapi.name).to.eql(Beta);
});
You can just reference the key value by using brackets around the name:
jsonData["restapi.name"]
object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]
this should do the trick
jsonData["restapi.name"]

Extract data from javascript

have a java script element , which when printed, gives [object Object].
console.log(data)
When i tried to JSON.Stringify(data) -it gives a json value:
{"key":"value"}
How to extract the value from the above object ?
JSON.stringify creates a JSON string representation of that JS object. If you want to use it as a JSON, you'd have to parse it again:
let data = '{"key": "value"}';
let dataJSON = JSON.parse(data);
console.log(dataJSON.key);
Outputs: value