I have the following JSON object
({
"codes": [ {
"code": {
"redeemed": "true", "retailer": "R1", "code": "ab11845b55b3ef1c3f137a35dbdfb270"
}
}, {
"code": {
"redeemed": "false", "code": "48c02f7bd35271de0aa215209b0a390f", "message": "code already used"
}
} ]
});
for (var code in data.codes) {
console.log(code) // prints 0
console.log(code[0].id) // prints 0
}
How can I access the inner objects separately ?
To output each individual "code" object:
// First, assign your data to a variable:
var data = ({
"codes": [ {
"code": {
"redeemed": "true", "retailer": "R1", "code": "ab11845b55b3ef1c3f137a35dbdfb270"
}
}, {
"code": {
"redeemed": "false", "code": "48c02f7bd35271de0aa215209b0a390f", "message": "code already used"
}
} ]
});
// (I use the "c" temprary variable here because it's shorter)
var c = data.codes;
// Loop through all the codes.
for (var i = 0; i < c.length; i++) {
// Log the specific code at [i].
console.log(c[i].code); // Output a "code" object.
}
You can then use:
c[i].code.redeemed;
c[i].code.retailer;
c[i].code.code;
c[i].code.message;
These will however return undefined when they're not set as a property of the specific "code" object.
Working example
assuming what you had added:
window.json_obj = ({"codes":[{"code":{"redeemed":"true","retailer":"R1","code":"ab11845b55b3ef1c3f137a35dbdfb270"}},{"code":{"redeemed":"false","code":"48c02f7bd35271de0aa215209b0a390f","message":"code already used"}}]});
console.log(json_obj.codes[0]['code']['code']);
// or
// console.log(json_obj.codes[0].code.code);
jsFiddle demo
console.log( obj.codes[0].code.retailer );
console.log( obj.codes[1].code.message );
Outputs
R1
code already used
None of the objects have an id property.
First:
Your JSON should not be in the parens, if you have no reason for it to be:
(<JSON>);
If that's all you're doing, it isn't going to let you access it.
You need to assign it to a variable...
var data = { codes : [ { code : "...", ...}, ... ] };
Once you do that, you have access like:
data.codes[i].code.code;
data.codes[i].code.redeemed;
PS: if it's not a full string
'{ "codes":[{"code":"...",...},...]}'
then it's not a JSON object, it's a JavaScript object.
Yes, that sounds picky.
But it all comes down to if you need to parse it and how, before you can use it properly.
the for (var stuff in whatever) returns you the index of the object.
So basically, to access your object you have to do
console.log(data.codes[code]);
console.log(data.codes[code].id);
and please format your json in a readable way next time, hard to read here :)
Related
Updated see below
I am in the process of creating a Mock API in Node.js. I have 3 files located in my apps json folder that the values token, id and session need to be updated all with the same key.
Here is an example of the 3 files. /json/standardsession.json
{ "token": "this needs manual edited value", "session": { "dlt": true, "start": 5280000, "end": 6000000 },
/json/session.json { "token": "this needs to be same value", "id": "this needs to be same value as token", "warning": "", "resident": { "id": 180161922, "resident_id": 264257672, "name": "John doe", "active": true,
},
/json/start.json
{ "code": 5, "error": null, "session": { "session_id": "this needs to be same value", "start_time": "2022-03-22T15:50:42.000Z", "status": 3 } }
How would I write a function that would update all 3 files with my set value in there respective places but not update all the other keys with the same ID like shown in sessions.json file above with the ID field also showing in residents. That doesn't get updated.
Is is possible to make a form that I can input the value into instead of a function that would update all 3 files with me manually inputting the data I want in it?
Both form and function help would be greatly appricated.
Thank you
Update:
After a few changes to code. I now get the following error. My code is posted below.
undefined:1
[object Object]
SyntaxError: Unexpected token o in JSON at position 1
const fs = require("fs")
//provide this function with a dictionary like
// give it your manual token value
function updateToken(token){
let rawdata = fs.readFileSync('json/standardsession.json');
let obj = JSON.parse(rawdata);
obj.token = token
fs.fileWrite('json/standardsession.json', obj, '')
let rawdata2 = fs.readFileSync('json/session.json');
let obj2 = JSON.parse(rawdata2);
obj2.token = token
obj2.id = token
fs.fileWrite('json/session.json', obj, '')
let rawdata3 = fs.readFileSync('json/start.json');
let obj3 = JSON.parse(rawdata3);
obj3.session.session_id = token
fs.fileWrite('json/start.json', obj, '')
}
You most likely want to create a function in your app.js code.
Let me know if I have misunderstood your question but this is the function I wrote for you below:
const fs = require("fs")
//provide this function with a dictionary like
// give it your manual token value
function updateToken(token){
let rawdata = fs.readFileSync(../json/standardsession.json);
let obj = JSON.parse(rawdata);
obj.token = token
fs.fileWrite(../json/standardsession.json, obj)
let rawdata = fs.readFileSync(../json/session.json);
let obj = JSON.parse(rawdata);
obj.token = token
obj.id = token
fs.fileWrite(../json/session.json, obj)
let rawdata = fs.readFileSync(../json/start.json);
let obj = JSON.parse(rawdata);
obj.session.session_id = token
fs.fileWrite(../json/start.json, obj)
}
}
Then to call this function to update your JSONs in code.
Write:
updateToken('my new token value');
I successfully (tested) call an ajax request to a php script. This is the portion of code i need to make working:
success: function (response, status) {
$.each(response, function (i, item) {
alert(item.id);
item.id is just...nothing.
This is the generated - json_encoded array by php page:
[
{
"conto": "1"
},
{
"id": "4",
"activity_id": "50",
"path": "Testo/base.png",
"title": "Ffgf",
"descrizione": "Tttt"
},
{
"id": "8",
"activity_id": "50",
"path": "Testo/61FCFUX_IMG_0536.PNG",
"title": "Hggggg",
"descrizione": "Tgg"
}
]
What do I do wrong?
p.s: if you noticed, this is an array merge between two arrays: the first one just reports "conto" in in, the other one is a list generated by fetching elements by database.
Your first array not containing id so you are getting undefined value. Skip first array:
$.each(response, function (i, item) {
if(i==0)
{
alert(item.costo);
}
else
{
alert(item.id);
//Or better to use console
console.log(item.id);
}
});
I believe your issue is with your reference. Since your JSON object contains an array you will need to reference it with subscripts. Try changing item.id to item[i].id. That way as the each function iterates through the array, it can reference the id field in each object.
Edit: Here's working code.
$(document).ready(function (){
var source = '[{"conto":"1"},{"id":"4","activity_id":"50","path":"Testo\/base.png","title":"Ffgf","descrizione":"Tttt"},{"id":"8","activity_id":"50","path":"Testo\/61FCFUX_IMG_0536.PNG","title":"Hggggg","descrizione":"Tgg"}]';
source = JSON.parse(source);
var cellcount = length(source);
for(var i = 0; i < cellcount; i++){
console.log(source[i].id);
}
});
function length(obj) {
return Object.keys(obj).length;
}
I have the following deocoded JSON array.
I need to access the "type" inside the context, as well as I need to loop through each of the values in the payload. How do I do that?
{
"RequestHeader":
{
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context" :
{
"type": "friends,circles"
}
"payload" [ {12345},{12345} ,{2345} ]
}
I tried the following, but it doesn't work
$decoded = json_decode($json_string);
for ($i=0;$i<payload.length;++$i)
{
$id=$decoded->payload[$i];
//do some operation with the id
}
First of all the JSON you provided is invalid. Supposedly the valid one should look like this
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
After you've fixed the problem with JSON provider it will be quite easy to access data
<?php
$json = <<<'JSON'
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
JSON;
$data = json_decode($json, true);
$type = $data['context']['type'];
var_dump($type);
foreach($data['payload'] as $id) {
var_dump($id);
}
Remember to make sure you check that the data actually exists before accessing it, e.g. isset($data['context']['type']) unless you are absolutely sure in it's integrity.
When you use json_decode method, the output will be nested arrays
So for example to access context type you need to do the following
echo $decoded["context"]["type"];
And to loop on payload you need to do the following
for ($i=0;$i<$decoded["payload"].length;++$i)
{
$id=$decoded["payload"][$i];
//do some operation with the id
}
can somebody tell me where I'm making the error in the following code? I want to read the title of the 1 Position in the json Array.
<script>
$(document).ready(function(){
$('#loading').click(function(){
var NpPData = [
{
"title": "Professional JavaScript",
"author": "Nicholas C. Zakas"
},
{
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan"
},
{
"title": "High Performance JavaScript",
"author": "Nicholas C. Zakas"
}
];
var NpPDataJSON = JSON.stringify(NpPData);
alert(NpPDataJSON);
$.post("prueba.php", NpPDataJSON, function(r){
$('#result').html('Answer from server: '+r);
},
'json').error(function(e){
alert('FAiled: '+e.statusText);
});
});
});
</script>
And PHP:
$json = $_POST['NpPDataJSON'];
$data = json_decode($json);
echo $data[1]['title'];
Set second parameter to TRUE to have json_decode() to return an array instead of an stdClass object:
$json = $_POST['NpPDataJSON'];
$data = json_decode($json, true); // note the second argument
echo $data[1]['title']; // returns 'JavaScript: The Definitive Guide'
When TRUE, returned objects will be converted into associative arrays.
Also, as per #Stryner's comment, it seems you have misused the $.post() function. You need to set a name to the data you are passing to the server and therefore, pass an object instead of a variable:
$.post("prueba.php", {NpPDataJSON: NpPDataJSON}, function(r){/* ... */}, 'json');
I have Express running on a custom node API that breaks down a large JSON into bite sized chunks for mobile usage.
One of the section goes through a mass of items and returns only one of them. However the returned data is still wrapped in [ .. ] which makes working with it tough.
My NODE.JS code snippet that deals with my routed request
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
res.json(with_operatorCode);
});
so if you access the url
http://(domain)3000/ppm/summary/operators/25
the following data is returned
[
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendInd": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
]
How can I break that object out of the [ .. ] so it is not returned as an array object and only shows as
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendInd": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
Alternativly, how can I work with the [ .. ] object in PHP? When I am trying to echo it using
$operatorJSON=file_get_contents("operator.json");
$operator=json_decode($operatorJSON);
echo $operator->PPM->text;
It errors if the JSON has the [ ]
I suspect it is being treated as an array object
UPDATE : I tried to flatten the array
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
var obj = arr.reduce(function(x, y, i) {
x[i] = y;
return x;
}, {});
res.json(obj(with_operatorCode));
});
but the object returned is still in [ ]
If i understand correctly , i think the most easy way is use the index to get the element in array
res.json(with_operatorCode[0]);
Of course, the [foo] denotes that it is an array.
You could address the item as [0], but that is more likely to cause an error, if no item exists in the filter:
On the php side:
$operator=json_decode($operatorJSON);
echo $operator[0]->PPM->text;
On the Node side:
res.json(with_operatorCode[0]);
The smarter thing to do would be to handle it as an array:
$operator=json_decode($operatorJSON);
if (is_array($operator) && count($operator))
{
echo $operator[0]->PPM->text;
}
Or, if filter may give you more than one:
$operator=json_decode($operatorJSON);
foreach ($operator as $op)
{
echo $op->PPM->text;
}
Try for this:
function toObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i)
obj[i] = arr[i];
obj rv;
}