Update multiple JSON files in Node.js - php

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

Related

The argument type 'String' can't be assigned to the parameter type 'Uri'. Flutter

I'm having a trouble, why I'm getting this error in my app flutter main.dart
I just follow this reference link. It would be great if anybody could figure out, thank you so much in advance!.
Here's the error part
Future<List> _login() async {
final response = await http.post("http://10.0.2.2/my_store/login.php", body: {
"username": user.text,
"password": pass.text,
});
You need to parse your URLs now, use it like this:
Future<List> _login() async {
final response = await http.post(Uri.parse("http://10.0.2.2/my_store/login.php"), body: {
"username": user.text,
"password": pass.text,
});

PHP/Swift JSON Serialization on array of list of items results in zero elements

Hi I'm new here and very new to programming but will try to make this issue as clear as possible. Essentially I have a table created from a SQL query that gives a list of items/objects in a user's inventory based on their userID. The table looks something like this (where userID is 5) - apologize as I do not have enough rep to post pictures yet:
user 5's inventory
I was going to have a tableView in Swift populate that table but when I ran into issues with converting the response I instead just made a separate ViewController with a button to run the checkInventory function, so I can print out all the data and see where the issue is.
First here is my PHP function to check the inventory:
public function getUserInventory($userID) {
$returnValue = array();
$sql = "select aObjects.objectID, objectDescription from aUsers join aInventory on aUsers.userID = aInventory.userID join aObjects on aInventory.objectID = aObjects.objectID where aUsers.userID='" .$userID. "'" ;
try {
$statement = $this->conn->prepare($sql);
$statement->execute();
$statement->bind_result($objectID, $objectDescription);
}
catch (PDOException $e)
{
print $e->getMessage();
}
$result = $statement->get_result();
if ($result != null && (mysqli_num_rows($result) >= 1))
{
$row = $result->fetch_all(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
The PDO Exception line might be unnecessary/incorrect because I'm using mysqli but regardless here is the other PHP file that calls that function:
<?php
set_include_path('.:/testservice/');
$data = json_decode(file_get_contents('php://input'), true);
$userID = $data["userID"];
//$userID = htmlentities($_GET["userID"]); <--- for testing
include 'Conn.php'; /* connection file */
include 'aSQLDao.php'; /* rest of php file */
$dao = new aSQLDao();
$dao->openConnection();
$userInventory = $dao->getUserInventory($userID);
echo json_encode($userInventory);
return;
$dao->closeConnection();
?>
I am 90% sure the root of my issue lies in my PHP not giving out a JSON output that Swift can read properly. When I use postman to check the PHP with userID = 5, I get an object that looks nice but seems to have an underlying problem with its format:
[
{
"objectID": 1,
"objectDescription": "alien"
},
{
"objectID": 2,
"objectDescription": "forestMonster"
},
{
"objectID": 10,
"objectDescription": "tank"
},
{
"objectID": 9,
"objectDescription": "fish"
}
]
In swift I have just been setting the variable userID to 5 to test it out and going through the general request + serialization process:
#IBAction func inventoryButtonTapped(_ sender: Any) {
let userID = "5"
let myURL = URL(string: "http://myIP/testservice/inventoryCheck.php");
var request = URLRequest(url:myURL!);
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let getString = ["userID": userID] as [String: String]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: getString, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
displayMessage(userMessage: "Something went wrong")
return
}
let task = URLSession.shared.dataTask(with: request) {
data, response, error in
if error != nil {
self.displayMessage(userMessage: "Could not perform")
print("error=\(String(describing: error))")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
print(json)
There's more but based on breakpoints I am unable to convert this data correctly at the JSONSerialization step. When using "as! NS Dictionary" I get the "Could not cast value of type '__NSArrayM' (0x10ad29a88) to 'NSDictionary' (0x10ad2b1a8)." error.
When using "as! NSArray" I get an empty set of parantheses. I tried also using Array> which resulted in an empty set of brackets. I have tried setting userID to int as well but from what I've read that should not affect this.
I apologize if there is any details missing here. Since it seems to be a pretty simple case of transferring a SQL table to UITableView I assume there is either a major piece I am missing or I am doing the wrong set of operations.
UPDATE: I did figure out that the Server is just not receiving my userID key correctly which is strange but at least hopefully rules out that PHP or Swift is incorrect - assume both answers provided would work if the variable was sent correctly to the script
SOLVED: For whatever reason this issue was solved when changing the HTTPRequest from GET to POST - seemed to be an issue with the PHP input not working for a GET request. I'll update this post with more specific details for future reference when I figure out how to make the GET request work properly as this should be GET and not POST. Both answers provided are right in terms of changing NSDictionary to NSArray or [[String:Any]]
The deserialization line is here:
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
You are trying to force-cast to NSDictionary. The problem is your data structure is an Array.
[ // this will convert to an array
{ // this will convert to a dictionary
"objectID": 1,
"objectDescription": "alien"
},
...
]
You have a couple of choices. You can change her JSON to produce a Dictionary, or you can change your deserializer to expect an Array.
Here's the second case in code:
//: Playground - noun: a place where people can play
import UIKit
var dataStr = """
[ { "objectID": 1, "objectDescription": "alien" }, { "objectID": 2, "objectDescription": "forestMonster" }, { "objectID": 10, "objectDescription": "tank" }, { "objectID": 9, "objectDescription": "fish" }]
"""
var data = dataStr.data(using: .utf8)
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
And the result:
I guess you should first get your JSON-parsing code in order before you start to deal with your dataTask and such. Throwing in some Codable to become more Swifty you get something like
import Cocoa
let jsonData = """
[
{
"objectID": 1,
"objectDescription": "alien"
},
{
"objectID": 2,
"objectDescription": "forestMonster"
},
{
"objectID": 10,
"objectDescription": "tank"
},
{
"objectID": 9,
"objectDescription": "fish"
}
]
""".data(using: .utf8)!
struct MyObject: Codable {
let id: Int
let description: String
private enum CodingKeys: String, CodingKey {
case id = "objectID"
case description = "objectDescription"
}
}
do {
let obj = try JSONDecoder().decode([MyObject].self, from:jsonData)
print(obj)
} catch {
print(error)
}
This will give you much more handy Swift objects with minimal effort and JSONDecoder would usually tell you if something is wrong with the JSON delivered (which there is not in this case).
With this in place you should print your raw data (by converting it into a String before doing so) in order to know what you throw at your parser (JSONDecoder).

CodeIgniter: Select the same like parameter on JSON list

I'm trying to use tokeninput from jQuery Token input, but the data is from the API. I already got the data from API and made a JSON list (see below).
When a user inputs in my token input, it will select from the JSON list, like user/auto_unit?queryParam=q for example. It already gets the user input correctly, but it still returns all data, even those that do not match the user input.
What I want is when the user searches for "Sosiologi", the only values that would show are those string which have "sosiologi" in them.
Is it possible to get only the same values and how can I do that? Thanks in advance!
My JSON list:
// 20170401095401
// http://exp.uin-suka.ac.id/aspirasi/user/auto_unit?queryParam=Filsafat%20Agama
[
{
"id": "UA000001",
"name": "Filsafat Agama"
},
{
"id": "UA000002",
"name": "Perbandingan Agama"
},
{
"id": "UA000003",
"name": "Ilmu Al-Qur'an dan Tafsir"
},
{
"id": "UA000004",
"name": "Sosiologi Agama"
},
{
"id": "UA000005",
"name": "Matematika"
},
{
My JSON code to get the list
function auto_unit() {
$data['unit'] = $this->m_simpeg->getAllUnit();
foreach ($data['unit'] as $key ){
$row['id']= $key['UNIT_ID'];
$row['name']= $key['UNIT_NAMA'];
$row_set[] = $row;
}
echo json_encode($row_set);
}
Model to get API M_simpeg.php:
public function getAllUnit(){
return $this->s00_lib_api->post_api(
1001, 1, null,
URL_API_SIMPEG.'simpeg_mix/data_view'
);
}
Check your server side code as it is not filtering the array.
Codeigniter sample code
<?php
function filter(){
$queryParam=$this->input->get('queryParam');
$res=$array.filter($queryParam);
return $res;
}
?>

Why json_decode doesn't work?

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

Acessing a JSON Object using Javascript

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 :)

Categories