I have data structure as below
{
status: false,
executed: true,
output : "Service is under maintenance [ {"command" :"uptime", "output" :"connection timeout"}] - exit status 3
}
I am trying to extract [ { "command" :"uptime", "output" :"connection timeout" }] from above data structure. if it is clean it be using regular dot walking with parse.
As this is not in proper format, I am looking for suggestions only to extract valid data structure.
Any suggestions greatly appreciated.
Thank you.
use indexOf("[") and lastIndexOf("]") to substring the string then use JSON.parse to parse the jsonstring ,then you will get [ { "command" :"uptime", "output" :"connection timeout" }];
hope it would help you
You can use string split functions in JavaScript to split the output string and then Parse the JSON String as a valid JSON. Hope the below code will help you.
var inputJson ={
status: false,
executed: true,
output : 'Service is under maintenance [ {"command" :"uptime", "output" :"connection timeout"}] - exit status 3'
}
var outputJson = JSON.parse(inputJson.output.split("[")[1].split("]")[0]);
console.log(outputJson.output);
Assuming output is a string from Service to status 3...
Here is a function to "clean" your data. I added a condition in case the data isn't "messed" ;)
let messedData = {
status: false,
executed: true,
output: 'Service is under maintenance[{"command": "uptime","output": "connection timeout"}] - exit status 3 '
}
function clean(data){
if(typeof(data.output) === "string"){
data.output = JSON.parse(data.output.match(/\[.+\]/)[0])
}
return data
}
console.log(clean(messedData))
Related
I am passing the following from my Django back-end to my front-end in order to dynamically build a form :
{
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
Within the browser console, if I pass :
MyJSON = {
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
Then I can access each value properly, for example, MyJSON.access_key returns 93ec6137de00eacee6f8 perfectly within the console.
However, from my Javascript, I am unable to access any of those values as i get an "undefined".
var obj = JSON.parse(MyJSON)
console.log(obj) // returns the whole JSON String
console.log(typeof(obj)) // returns 'string'
alert(obj[0]) // returns "{", the very first character of the 'string'
alert(obj.access_key) // returns "undefined".
- How can access each Key and Value from MyJSON from my javascript? (not JQuery)
Note that I have reviewed many similar article but I must be missing the obvious ...
Hope you can assist !
Thanks in advance.
EDIT :
I have a list of Fields and a list of Values which i then merge into the below (pass the JSON Validator on https://jsonlint.com/):
{'access_key': '93ec6137d70aada23400eacee6f8', 'profile_id': '7851E53E-96BB-4D4-BD5-0FE61CC15D64', 'transaction_uuid': '00939a90-db7b-41cb-af45-669ec5cc69e8', 'signed_field_names': 'bill_to_forename,bill_to_surname,bill_to_email,bill_to_phone,bill_to_address_line1,bill_to_address_city,bill_to_address_postal_code,bill_to_address_country,transaction_type,reference_number,payment_method,amount,currency,locale,card_type,card_number,card_expiry_date', 'unsigned_field_names': 'card_type,card_number,card_expiry_date', 'signed_date_time': '2021-05-23T16:20:17Z', 'bill_to_forename': 'John', 'bill_to_surname': 'Doe', 'bill_to_email': 'null#cfgfg.com', 'bill_to_phone': '07922889582', 'bill_to_address_line1': '123 Random Street', 'bill_to_address_city': 'London', 'bill_to_address_postal_code': 'RG1T3X', 'bill_to_address_country': 'GB', 'transaction_type': 'sale', 'reference_number': 'o6yejf', 'payment_method': 'card', 'amount': '100', 'currency': 'USD', 'locale': 'en', 'card_type': '001', 'card_number': '4456530000001096', 'card_expiry_date': '12-2026', 'signature': 'Un5gNYB5qZaRazzCDWqrdZuNkTRARIcfAt9aF2a1wbY='}
Back-end Code
FieldList = ['access_key', 'profile_id', 'transaction_uuid', 'signed_field_names', 'unsigned_field_names', 'signed_date_time', 'bill_to_forename', 'bill_to_surname', 'bill_to_email', 'bill_to_phone', 'bill_to_address_line1', 'bill_to_address_city', 'bill_to_address_postal_code', 'bill_to_address_country', 'transaction_type', 'reference_number', 'payment_method', 'amount', 'currency', 'locale', 'card_type', 'card_number', 'card_expiry_date', 'signature']
ValueList = ['93ec6137d0aada23400eacee6f8', '7851E53E-96BB-4DF4-BD55-0FE61CC15D64', 'c4fe96b0-063f-4b94-a6a5-2137bb796bd9', 'bill_to_forename,bill_to_surname,bill_to_email,bill_to_phone,bill_to_address_line1,bill_to_address_city,bill_to_address_postal_code,bill_to_address_country,transaction_type,reference_number,payment_method,amount,currency,locale,card_type,card_number,card_expiry_date', 'card_type,card_number,card_expiry_date', '2021-05-23T16:27:24Z', 'John', 'Doe', 'null#cyrce.com', '07922889582', '123 Random Street', 'London', 'RG1T3X', 'GB', 'sale', 'xl42fn', 'card', '100', 'USD', 'en', '001', '4456530000001096', '12-2026', 'vvb73h0GUpzUrvoG9VDaMc3vQRV5GsL4QTATc7IrrPA=']
NewFormat = dict(zip(FieldList, ValueList))
MyJSON = json.dumps(NewFormat, indent=4)
return JsonResponse(MyJSON, safe=False)
Apologies for the large amount of data.
I am somehow forced to use "safe=False" in my Python back-end otherwise I end up with :
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/Documents/Droplet/Droplet/Harness/sasop2.py", line 543, in signsasop
return JsonResponse(FinalJSONObject)
File "/home/pi/.local/lib/python3.7/site-packages/django/http/response.py", line 561, in __init__
'In order to allow non-dict objects to be serialized set the '
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
Since I am passing safe=False, is that why my front-end does not get the MyJSON as... JSON?
Would this be the root cause of the issue?
Front-End Sample :
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
console.log('%c Processed Data \n',
'background: #000000; color: #FFFFFF; font-size: 30px'
,xhr.response);
// Dynamically create the ReconstructedForm
RawProcessedData = xhr.response
console.log(RawProcessedData)
// Convert to JSON
var obj = JSON.parse(RawProcessedData)
console.log(obj)
console.log(typeof(obj))
alert(obj[0])
alert(obj.access_key)
Thanks a lot for your quick input !
As per deceze's answer, I was essentially double parsing both in the back and front end for no reasons.
Removing the json.dumps from the backend allows the JSON object to be passed and managed in the front end without issue.
I have the same issue when i started developing on Django. If you need to pass dictionarys from django to javascripts, the best thing to do is just using django rest framework. It serialize ( in other words, it transform any data into a dictionary/json ) any given data from a model.
But if you want to make this without Django Rest, you should use fetch on javascript. This fetch ( also called as a "Promise") communicate with the backend ( in this case, Django ) and it GET or POST data from the frontend. I will give you an example.
Supose you have this on views.py:
from django.http.response import JsonResponse
def getJSON(request):
MyJSON = {
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
return JsonResponse(MyJSON)
And the you can link that to the urls.py like this:
urlpatterns = [
path('get-json', views.getJSON, name="get-json")
]
Then you can GET that JSON by doing this on your javascript:
function getDataJson(){
let url = 'get-json'
fetch(url,{
headers: {
"Content-type": "application/json",
},
})
.then(response => response.json())
.then(data=> console.log(data))
}
This will console log your data.
I have a problem with parsing an XML file.
I want to remove strings with characters like \t\n.
XML File: http://ftp.thinkimmo.com/home/immoanzeigen24/immo.xml
{
trim: true,
normalize: true,
attrValueProcessors: [cleanValue, name => name],
valueProcessors: [cleanValue, name => name]
}
cleanValue:
const cleanValue = value => {
return value.toString().trim().replace("\t","atest");
};
I tried cleaning it with a lot of regex I've found online - but value always stays like following:
"verwaltung_objekt": {
"objektadresse_freigeben": "0",
"verfuegbar_ab": "nachaasjkdhkjshadjkashdAbsprache",
"bisdatum": "2016-01-15",
"min_mietdauer": "\n\t\t\t\t",
"max_mietdauer": "\n\t\t\t\t",
}
This is a difficult one!
I'd suggest following a simple strategy and pre-processing the xml data before you parse it.
This should resolve your issue at least.
If you just do something like:
function trimXml(xml) {
return xml.replace(/>\s+</g, "><");
}
xml = trimXml(xml);
Then parse the trimmed xml data. You should see the output now looks like so:
"verwaltung_objekt": [
{
"objektadresse_freigeben": [
"1"
],
"abdatum": [
"2017-03-01"
],
"min_mietdauer": [
""
],
"max_mietdauer": [
""
]
}
],
Which is a bit more like what you want!
The script below is supposed to return a CSV of values I want from mongo, all the data I want is returned, but two items are in a different format, and try as I might I cannot get the value only.
Question 1: The first returned item "$_id", returns ObjectId("5a4b7775d9cc09000185b908") but I want to get ONLY the value 5a4b7775d9cc09000185b908. Every time I try to parse it or use valueOf, it returns a blank value.
Question 2: The 4th item I am requesting is supposed to be a time format of how long something took using the two date values {$subtract: [ "$finished", "$started" ] } (start and finish times). What I get back is NumberLong(5844) which should be just the milisenconds.
Script
var cur=db.submissions.aggregate(
[
{$match: { started: {'$gte': ISODate('2018-01-02 01:01:01.001'), '$lte': ISODate('2018-01-02 13:15:59.999' ) } } },
{$project: {
data: [
"$_id",
{$dateToString: { format: "%Y-%m-%d %H:%M:%S", date: "$started" } },
{$dateToString: { format: "%Y-%m-%d %H:%M:%S", date: "$finished" } },
{$subtract: [ "$finished", "$started" ] },
"$inputs.x12InputFile.size"
]
}
}
]
)
cur.forEach(function(doc) {print(doc.data)})
Current Results
ObjectId("5a4b7775d9cc09000185b908"),2018-01-02 12:13:42,2018-01-02 12:13:48,NumberLong(5844),5322
ObjectId("5a4b77d530391100017d92df"),2018-01-02 12:15:18,2018-01-02 12:15:26,NumberLong(8593),5178
Expected Results
5a4b7775d9cc09000185b908,2018-01-02 12:13:42,2018-01-02 12:13:48,5844,5322
5a4b77d530391100017d92df,2018-01-02 12:15:18,2018-01-02 12:15:26,8593,5178
Any help would be appreciated. I am quite the newbie at scripting mongo queries, so details/examples in responses help if at all possible.
I wouldn't use aggregation framework for formatting results. You can't convert from ObjectId to string in aggregation piepline anyways.
var cursor = db.submissions.find({started:{'$gte': ISODate('2018-01-02
01:01:01.001'),'$lte': ISODate('2018-01-02 13:15:59.999' )}},{started : 1,
finished : 1, "inputs.inputFile.size" : 1});
cursor.forEach( function(doc) {
var arr=[];
arr.push(doc._id.str);
arr.push(doc.started.toISOString());
arr.push(doc.finished.toISOString());
arr.push(doc.finished.getTime() - doc.started.getTime());
print(arr)
});
I'm writing a simple JS app that takes in a JSON file, displays the information to the user and allows them to modify it, and then allows them to re-export the JSON. However, the JSON that is being brought in is multi-line; each key/value is on its own line. When I use .stringify to output the JSON, it all appears on one line. Is there any way for the stringify method to separate the lines?
JSON Structure:
{"Title":
{"lvlOne":[
{"key":"val"},
{"key":"val"},
{"key":"val"}
],
"lvl2":[
{"key":"val"},
{"key":"val"},
{"key":"val"}
]}
}
But when I output, it all shows:
{"Title":{"lvlOne":[{"key":"val"},{"key":"val"},{"key":"val"}],"lvl2":[{"key":"val"{"key":"val"},{"key":"val"}]}}
You can use the space parameter of the stringify method. From the official page, here is the relevant excerpt:
JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'
you can also use.
var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, '\t');
console.log(json);
Or even better, the count of spaces in the indentation:
var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, 2);
None of the above worked for me the only thing that worked for me was
await fs.promises.writeFile('testdataattr.json',JSON.stringify(datatofile, null,'\r\n'),'utf8') ;
I am using the auto complete plugin by Devbridge and I have it all installed here is my code:
$(document).ready(function(){
$('#request_task').autocomplete({
serviceUrl: '<%= ajax_path %>',
minChars:1,
width: 300,
delimiter: /(,|;)\s*/,
deferRequestBy: 0, //miliseconds
params: { artists: 'Yes' },
});
});
This request hits my rails action and returns this json. there is only one object returned but most of the time there will be more then 1...this was just a test case:
[
{
"user": {
"salt": "somthing",
"name": "john",
"encrypted_password": "92dadsfa6b001ffe71c3c1d8e9fb76c42d1c8afeffa739de9063d94206c",
"created_at": "2010-09-10T14:10:54Z",
"updated_at": "2010-09-10T14:10:54Z",
"admin": null,
"id": 1,
"remember_token": "c945522b3eb0a25e36bb39155fc05b3eec301ac5e2196956f2e6f86b4b22c987",
"email": "test#gmail.com"
}
}
]
I can clearly see the request in firebug but I am not getting anything for the autocomplete and it errors out...Am i missing anything...My error is
a.suggestions is undefined
I think you need to read a little further down the developers page as your response is in the wrong format:
Web page that provides data for Ajax
Autocomplete, in our case
autocomplete.ashx will receive GET
request with querystring ?query=Li,
and it must return JSON data in the
following format:
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}
Notes:
query - original query value
suggestions - comma separated array of suggested values data
(optional) - data array, that contains values for callback function when data is selected.
Sincere advice , dont construct JSON Strings. Please go for an API.
If you are using java, check this out http://www.json.org/java/
and make sure to set content-type in response as application/json
YOUR JSON is in a wrong format
Check their correct format
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}