We have empty JSON file
I want to write new JSON objects in this file, and get from it Array of JSON objects (and after simply append new JSONs to array by 'push')
I write to the file incoming JSON object:
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
where
updatedJsonStr = JSON.stringify({"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"});
So in the file we see added object.
After we get from the file our JSON objects:
tasksJsonObj = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
Append new JSON object as string and write it again:
updatedJsonStr = JSON.stringify(tasksJsonObj) + ',' + JSON.stringify(newJsonTask);
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
So we see 2 JSON objects in the file.
!But when I try to read file with 2 JSON objects - I got an error when reading JSON from the file ([SyntaxError: Unexpected token ,]):
try{
tasksJsonObj = JSON.parse(fs.readFileSync(tasks, "utf-8"));
console.log('aaaaa' + JSON.stringify(tasksJsonObj));
return true;
}catch (err) {
console.log("its not ok!");
console.log(err);
return false;
}
Your JSON formation is wrong,
{"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}, {"newisCompleted":false,"task":"dfgdfg","date":"25.06.2015"}
this is what you will get after concat two JSON stringify, which is also invalid.
Your JSON should be like this
[ {"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}, {"newisCompleted":false,"task":"dfgdfg","date":"25.06.2015"} ]
for that you can do something like this
var tasks = [];
tasks.push( {"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}) );
so your update jsonstr would be
updatedJsonStr = JSON.stringify( tasks );
again if you want to append a new json string, you can do like this
tasksJsonObj = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
tasksJsonObj.push( newJsonTask );
and then stringify it and write it back to file.
If you are trying to "extend" the object:
https://lodash.com/docs#assign
deep extend (like jQuery's) for nodeJS
If you are trying to "push" new objects into an array, then you're almost there:
var updatedJsonStr = JSON.stringify([{"isCompleted":false,"task":"dfgdfg","date":"25.06.2015"}]);
fs.writeFileSync(tasks, updatedJsonStr, encoding='utf8');
var tasksJsonArr = JSON.parse(fs.readFileSync("tasks.json", "utf-8"));
tasksJsonArr.push(newJsonTask);
There's a little problem with what you are writing. If you want to have multiple JSONs next to each other, you should consider putting them into an array:
updatedJsonStr = [];
updatedJsonStr.push(JSON.stringify(tasksJsonObj));
updatedJsonStr.push(JSON.stringify(newJsonTask));
and then write them into file!
Related
I just can't find a working solution and implement in my format.
There is a JSON file which is returned to me by URL. Its format is:
{"success":true,
"data":[
{
"loadTimestamp":"2022-07-20T15:12:35.097Z",
"seqNum":"9480969",
"price":"45.7",
"quantity":"0.2",
"makerClientOrderId":"1658329838469",
"takerClientOrderId":"1658329934701"
},
{
"loadTimestamp":"2022-07-20T14:49:11.446Z",
"seqNum":"9480410",
"price":"46",
"quantity":"0.1",
"makerClientOrderId":"1658328403394",
"takerClientOrderId":"0"
}]
}
Due to the fact that it is returned via the URL, it is not possible to directly use the object, for example:
myobj['data']['price']
I have either a string of data that I can convert using JSON.parse() or an object right away.
But for some reason I can't use it directly.
As far as I understand, this is a JSON file inside which is an array of JSON data.
My goal is to display all the data from the array, while taking for example 2 values: price, quantity
How can I access the values that I want to get?
Ok I find, what I was looking for.
I return result not in json, but in text response.text()
After I did this, I create a new constant called res and put in it JSON.parse(data)
const url = 'https://myurl.com/'+pub_key
const response = await fetch(url)
let data = ''
if (response.ok) { data = await response.text() } else { console.log("Error HTTP: " + response.status) }
const res = JSON.parse(data)
After all this manipulations I can use my data with 2 ways:
console.log(res["data"][0]["price"])
console.log(res.data[0].price)
Or I can make a cocktail from it, by using my favorite blender :)))
if(res.success==true){
for(let item in res.data){
console.log(res.data[item].price,res.data[item].quantity)
}
}
the json data is
"{\"n925D\":1,\"t925D\":23.5,\"h925D\":3276.8,...
I'm replacing the symbol by
var results = post
.replace(/\{/g, '[[')
.replace(/\"/g, '\'')
.replace(/\,/g, '\'],[')
.replace(/\:/g, ',\'')
.replace(/\}/g, '\']]')
.replace(/\\([^u])/g, '$1')
;
console.log(results); shows
[['n925D','1'],['t925D','23.5'],['h925D','3276.8'],...
console.log(query.sql); shows
INSERT INTO table (did,val) SET '[[\'n925D\',\'1\'],[\'t925D\',\'23.5\'],[\'h925D\',\'3276.8\'],
how can I remove the \ actually...
You can't reliably parse JSON (or XML or HTML) with regexes. Instead, parse it, change the data, and re-emit it.
var jsonData = '{\"n925D\":1,\"t925D\":23.5,\"h925D\":3276.8,...';
// Parse it into a hash
var jsonParsed = JSON.parse(jsonData);
// Change the hash in jsonParsed to an array of arrays.
// Convert it back into JSON
jsonData = JSON.stringify(jsonObj);
I have a set of input data files in JSON and I am trying to replace a value present in a JSON file and use that value to do a post request in restAssured
The JSON file has
{
"items": [
{
"item_ref": 241,
"price": 100
}
]
}
jsonbody below is a String of the above JSON file
This is the code that fails:
JSONObject jObject = new JSONObject(jsonbody);
jObject.remove("item_ref");
jObject.put("item_ref","251");
System.out.println(jObject);
This is what I am getting:
{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
What I want is {"items":[{"item_ref":251,"price":100}]}
I also tried
JSONObject jObject = new JSONObject(jsonbody);
jObject.getJSONObject("items").remove("item_ref");
jObject.getJSONObject("items").put("item_ref","251");
System
But it says JSONObject["items"] is not a JSONObject.
All I need is to replace the 241 with 251. Is there an easier way to do this?
In general if we have a predefined JSON body file and if we want to replace some of the values in the body and use that in our POST calls within RestAssured, is there any easier way to do it?
The problem is - field item_ref and price are not in JSON Object as you think they are.
They are in JSON Array which contains JSON Objects. In order to modify that value, you have to get elements of the array and THEN execute very similar code you wrote.
Check this out:
JSONObject jObject = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
The output is:
{"items":[{"item_ref":251,"price":100}]}
Also, you can create a Hashmap:
HashMap<String,String> map = new HashMap<>();
map.put("key", "value");
RestAssured.baseURI = BASE_URL;
RequestSpecification request = RestAssured.given();
request.auth().preemptive().basic("Username", "Password").body(map).put("url");
System.out.println("The value of the field after change is: " + map.get("key"));
I am reading a JSON file using fs.readFileSync(fileName, 'utf8'); but the results include newline characters, and the output is getting like:
"{\r\n \"name\":\"Arka\",\r\n \"id\": \"13\"\r\n}"
How do I avoid these characters?
my local file looks like:
{
"name":"Arka",
"id": "13"
}
Its unnecessary to read JSON in using fs.readFileSync(). This requires you to also write a try/catch block around the fs.readFileSync() usage and then use JSON.parse() on the file data. Instead you can require JSON files in Node as if they were packages. They will get parsed as if you read the file in as a string and then used JSON.parse(), this simplifies the reading of JSON to one line.
let data = require(fileName)
console.log(data) // { name: 'Arka', id: '13' }
If you want to serialize the parsed JS object within data to a file without the new line & carriage return characters you can write the JSON string to a file using JSON.stringify() only passing in data.
const {promisify} = require('util')
const writeFile = util.promisify(require('fs').writeFile)
const data = require(fileName)
const serializeJSON = (dest, toJson) => writeFile(dest, JSON.stringify(toJson))
serializeJSON('./stringify-data.json', data)
.then(() => console.log('JSON written Successfully'))
.catch(err => console.log('Could not write JSON', err))
You could read the file and then remove them with a regex:
var rawJson = fs.readFileSync(fileName, 'utf8');
rawJson = rawJson.replace(/\r|\n/g, '');
Keep in mind though that for parsing JSON with JSON.parse, you don't need to do this. The result will be the same with and without the newlines.
I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)