So i have this JSON Structure, which i want to access:
data { payload: "{"state":{"reported":{"measuredata":{…
JSON.parse doesnt work, neither does JSON.stringify.
i only can access payload, if i go any further, i receive error or undefined:
data.payload // works
data.payload["state"] //undefined
data.payload.state // undefined
data.payload[0].state // undefined
data.payload[0]["state"] // undefined
what am i doing wrong?
the thing that i can see is that you have a bad format on your json data { payload: "{"state":{"reported":{"measuredata":{…
it hspuld be witouth the double quote that be after the word payload payload: "{"state"
you have to have something like this
payload: {"state"
You just need to use JSON.parse for payload json string value.
JSON.parse(data.payload).state;
Sample code for parsing.
var data = {
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":
{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":
{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
}
};
var data1 = JSON.stringify(data);
var data_final = JSON.parse(data1);
console.log(data_final.products.pic_id);
Related
I am having trouble accessing the data in this JS Object. I can get this data by accessing data.queryParams. But if I try to drill lower, I get undefined. Below is what shows up if I do a JSON.stringify(data.queryParams). I've tried data.queryParams.attributes, data.queryParams[0], data.queryParams.handle, etc. And I get undefined for all of them.
console.log(data)
Object {
"hostname": "127.0.0.1",
"path": null,
"queryParams": Object {
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"XXXXXXXXXXXX\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
},
"scheme": "exp",
}
console.log(data.queryParams)
Object {
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"42e97018b6604fe491b82b629ad65c23\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
}
i think something wrong with your response, your data is set as key of the Object.
const obj = {
"hostname": "127.0.0.1",
"path": null,
"queryParams": {
// below is your data as key
"{\"attributes\":[{\"handle\":\"email\",\"name\":\"Email\",\"value\":\"test#test.com\"},{\"handle\":\"fname\",\"name\":\"First Name\",\"value\":\"Luke\"},{\"handle\":\"lname\",\"name\":\"Last Name\",\"value\":\"Skywalker\"},{\"handle\":\"zip\",\"name\":\"Postal Code\",\"value\":\"73067-9895\"},{\"handle\":\"uuid\",\"name\":\"Unique Identifier\",\"value\":\"XXXXXXXXXXXX\"}],\"status\":[{\"group\":\"penguins\",\"subgroups\":[\"King penguins\"],\"verified\":true}]}": "",
},
"scheme": "exp",
};
let value = Object.keys(obj.queryParams)[0]; // <-- get your data
value = JSON.parse(value); // <-- set to JSON
console.log(value.attributes) // <-- test log attributes
but better if you can fix the response
Try with JSON.parse to convert your JSON string to an object, then you can access your data
let attributes = JSON.parse(data.queryParams).attributes;
console.log(attributes)
I am running into a problem where when I submit a "property listing" I get this response:
{"owner_id":"Batman","address":"test","state":"test","sale_price":"test"}
The thing is "owner_id" is supposed to equal or associate with owner's id in a different table/JSON file (e.g owner_id = owner.id), not a string in this case which is why the object is not saving on the back-end.
Is anyone in vanilla JavaScript able to show me an example on how to associate owner_id and owner.id?
It'd be more like :
{
owner: {
id: "Batman"
},
address: "test",
state: "test",
sale_price: "test"
}
You should take a look at : https://www.w3schools.com/js/js_json_objects.asp
EDIT: Not sure how you're fetching this data but it seems like you want to handle the response you're getting.
Here is a simple GET request using the fetch api:
fetch('http://example.com/heroes') //this is the path to your source where you're getting your response data
.then((response) => {
return response.json();
//above you return a promise containing your response data
//you can also handle your response before declaring it in a var here
})
.then((myJson) => {
//you have stored your response data as a var myJson
console.log(myJson);
//here you can work your response data in any way you need
// to show an example (not that you would do this) I've provided a owner object that checks if it's property is equal to the incoming data
var owner = {
"id": Batman,
}
if ( myJson.owner_id === owner.id ) {
//do something here
}
});
More info here.
I would like to store accounts in a json file.
Something like : accounts{[user: user1, email: email1], [user: user2. email: email2]}
Javascript file
Accounts = {
Nickname: form.getElementsByTagName('input')[0].value,
Email: form.getElementsByTagName('input')[3].value
};
var json = JSON.stringify(Accounts);
fs.appendFile('Accounts.json', json, function(err){});
When I add a second user this code make a new object and it looks like.
Json file
{"NickName": "user1", "Email": "Email1"}{"NickName": "user2", "Email": "Email2"}
Then, when I try to read the file and parse it I receive an unexpected error {
I think the Json file should look like
{
{"Name":"value"},
{"Name2":"value2"}
}
I fix the issue.
Here the solution with a mix of Michael Brune's solution.
// Read accounts.json
const Accounts = fs.readFileSync('Accounts.json', 'utf-8');
// Check if json file is empty
if(Accounts.length !== 0){
var ParsedAccounts = JSON.parse(Accounts);
}
else{
ParsedAccounts = [];
}
ParsedAccounts.push(Account);
const NewData = JSON.stringify(ParsedAccounts, null, 4);
// Write new data to accounts.json
fs.writeFileSync('Accounts.json', NewData);
Basically, I push the new data in ParsedAccounts then I write it in the json file.
Maybe there is another way, but if your file is pretty small, then try like this:
Accounts.json:
{
"other": "other data"
}
index.js
const fileData = fs.readFileSync('Accounts.json');
let parsedFileData
try {
parsedFileData = JSON.parse(fileData);
} catch (error) {
if (error instanceof SyntaxError) {
// Create empty object to append to since parse was not a success
parsedFileData = {};
// Create backup of old, possible corrupt file
fs.writeFileSync('Accounts.backup.json', fileData);
}
}
const newFileData = JSON.stringify({
...parsedFileData,
...newDataToAppend,
}, null, 4);
fs.writeFileSync('Accounts.json', newFileData);
First you can parse the file.
Assign new and old data to a object.
Then convert that to srting JSON.Stringify
The null and 4 are to write a nice pretty file
Then write it to the file directly.
I try send string to controller, the string is json format, when send to controller, i get error and can't decode my json string in that controller. I try to encode first in my controller, but still get error. And the error is
"json_decode() expects parameter 1 to be string, array given",
exception: "ErrorException",
here in my json string
"{ "data" :
[{
"id": "TNI01",
"jenis_bayar": "TUNAI",
"no_kartu": "kosong",
"nominal": "10000",
"seq": "1"
} ,
{
"id": "DEB01",
"jenis_bayar": "DEBIT BCA",
"no_kartu": "786382432432",
"nominal": "20000",
"seq": "2"
}]
}"
here the controller
public function ArrayPostToTablePembayaran(Request $request)
{
$data = json_decode($request->datajson, true);
foreach ($data->data as $datas)
{
$id = $datas->id;
$jenisbayar = $datas->jenis_bayar;
$nokartu = "";
if($datas->no_kartu == "kosong")
{
$nokartu ="";
}
$nominal = $datas->nominal;
$seq = $data->seq;
$this->PosToTablePembayaran1($id , $jenisbayar , $nokartu , $nominal , $seq);
}
}
and here the ajax script for parse json string to controller
function PembayaranKeDatabase1(arraystring)
{
$.ajax(
{
type : "POST",
url : "{{ url('/trx_bayar') }}",
data : { datajson : JSON.parse(arraydata) } ,
dataType: "json",
success: function(data){
},
error: function() {
}
});
}
thanks before
The main issue in your code that you try to decode json twice: in client js code and on server.
Let's inspect what you do:
JS function PembayaranKeDatabase1(arraystring) has an argument of type string, I presume. I also presume that arraystring is a JSON-string. So, you decode JSON-string to object with
JSON.parse(arraydata)
// btw shouldn't it be
//JSON.parse(arraystring)
So, here you send some plain object to server, not json.
Next, on server you try to decode again. But you receive an array in $request->datajson, as json is already decoded on client-side.
So, you can choose between two options:
Remove JSON.parse:
data : { datajson : arraydata },
and use json_decode on server.
Remove json_decode($request->datajson, true) on server. Iterate over your data as
// as $request->datajson is an array
foreach ($request->datajson['data'] as $datas) {
// use [] notation as you work with array, not object
echo $datas['id'];
}
I am using the node.js to interpret a JSON data, the data format is like this below
{
"href": "https://localhost/light/0000293D",
"i-object-metadata": [
{
"rel": "temperature",
"val": "244"
}
]
}
I can print the raw data using print (body)
to interpret data all works except printing the field i-object-metadata
var obj = JSON.parse(body);
console.log(obj.items); // works well
console.log(obj.i-object-metadata); // error
How could I interpret the JSON object like this i-object-metadata
Can't use the object shorthand in this case, you'll have to use the array notation:
console.log(obj['i-object-metadata'].val); // 244