How to remove " from json nested value - javascript

How do I remove special char " in data and origin value below?
EDIT:
I have added comma after blue before origin, the actual issue was how to make "[]" to [] after origin.
I want from this:
{
"data" : "[{
"color": "blue",
"origin": "[{"state" : "USA"}, {"state" : "AFRICA"}]"
}]"
}
To This:
{
"data" : [{
"color": "blue",
"origin": [{"state" : "USA"}, {"state" : "AFRICA"}]
}]
}

const strArr = "[{\"foo\": \"bar\"}]";
const arr = JSON.parse(strArr);
console.log(arr);
if that objects name is say "obj" you can do:
obj.data = JSON.parse(obj.data);
this will convert a valid json string into an array
Edit:
if you are just trying to make origin an array instead of a string (assuming valid json) it is probably best you just JSON parse the whole thing then set origin to JSON.parse(origin)
let data = "[{\"color\": \"blue\", \"origin\": \"[{\\\"state\\\": \\\"USA\\\"},{\\\"state\\\": \\\"AFRICA\\\"}]\"}]";
let obj = {
data: data
};
let objData = JSON.parse(obj.data);
objData[0].origin = JSON.parse(objData[0].origin);
console.log(objData);

Related

Parse string list in javascript

So when I retrieve a cookie in javascript I get it like this
"[\"name\"\054 \"name1\"\054 \"name2\"\054 \"name3\"\054 \"name4\"\054 \"name5\"]"
How to change it to be a list as below?
["name", "name1", "name2", "name3", "name4", "name5"]
const parsed = JSON.parse("[\"name\"\054 \"name1\"\054 \"name2\"\054 \"name3\"\054 \"name4\"\054 \"name5\"]");
console.log(parsed); // ["name", "name1", "name2", "name3", "name4", "name5"]
Your cookie was stored as a JSON string, so when you retrieve it you need to use JSON to turn it back into an array (a list). Make sure it isn't null first, though:
if (typeof retrievedCookie == "string") {
var myArray = JSON.parse(retrievedCookie)
} else {
// retrievedCookie is probably null or undefined
var myArray = []
}
Just parse it like this:
JSON.parse(list)

how to Convert JavaScript array (without object name) into json (with object name)?

I am reading a local csv file with ajax query , and then loading read values into an array.
This is how the string value looks like in the csv file :
"Tiger","Architect","800","DRP","5421","VFX"
after loading this string into the array , the array looks like this :
0: (6) ["Tiger", "Architect", "800", "DRP", "5421", "VFX"]
now I am trying to convert this above mentioned sting into a json object to look like this :
{
"data": [
{
"0": "Tiger",
"1": "Architect",
"2": "800",
"3": "DRP",
"4": "5421",
"5": "VFX"
}]
}
by having all the values inside one object data
I tried this :
var arrayToString = JSON.stringify(Object.assign({}, data1));
var stringToJsonObject = JSON.parse (arrayToString) ;
it converts the array to json, but with length 6 where as I need the length to be 1
any way to do this ?
I think you have almost done everything, when you create object - just wrap array in []
const arr = ["Tiger", "Architect", "800", "DRP", "5421", "VFX"];
var arrayToString = JSON.stringify(Object.assign({}, [arr]));
var stringToJsonObject = JSON.parse (arrayToString) ;
console.log(stringToJsonObject);
You can do this using Object.entries and Object.fromEntries.
const arr = ["Tiger", "Architect", "800", "DRP", "5421", "VFX"];
const result = {data: []};
result.data.push(Object.fromEntries(Object.entries(arr)));
console.log(result);

How to Turn a Multiple Array Object into Query String Parameters in JavaScript

I have the following object below with multiple arrays.
{
"services": [
{
"id": "100",
"name": "PIX"
},
{
"id": "200",
"name": "Rendimentos"
}
],
"channels": [
{
"id": "300",
"name": "Chat"
}
]
}
The idea is to generate query strings, something like that.
services=100&services=200&channels=300
I know you can do it with map and join, but I would know if it was with a pure object, now this format below, I'm confused
You can use URLSearchParams() API.
Iterate your data and append key/value pairs or map an entries array to pass to the constructor
I have no idea what determines the expected output you have shown from the data displayed so am using a simpler data structure for demonstration purposes.
You can combine with URL() API to create full url string as shown below also
const data = [
{name:'foo', value:10},
{name:'bar', value:20}
]
// Loop and append key/values
const params = new URLSearchParams();
data.forEach(e => params.append(e.name, e.value));
console.log('params:', params.toString());
// Alternate approach passing entries array to constructor
const params2 = new URLSearchParams(data.map(e => [e.name,e.value]));
console.log('params2:',params2.toString())
//Adding to a URL
const url = new URL('http://example.com')
url.search = params
console.log('Full url:',url)
Using the updated array data in question:
const data={services:[{id:"100",name:"PIX"},{id:"200",name:"Rendimentos"}],channels:[{id:"300",name:"Chat"}]};
const entries = [];
Object.entries(data).forEach(([k,arr])=> arr.forEach(({id}) => entries.push([k,id])));
const params = new URLSearchParams(entries);
const url = new URL('http://example.com')
url.search = params;
console.log(url)
Looks like you're hung up on trying to iterate an object with map() or join(), which you can't do directly. Instead you can use Object.entries to convert the object into an array and iterate that. Since there is a nested map() you can flat() it before join()
let obj = {
"services": [{
"id": "100",
"name": "PIX"
},
{
"id": "200",
"name": "Rendimentos"
}
],
"channels": [{
"id": "300",
"name": "Chat"
}]
}
let queryString = Object.entries(obj).map(s => s[1].map(e => `${s[0]}=${e.id}`)).flat().join('&')
console.log(queryString)

Merge json flowfiles in NiFi using Executescript with Javascript

I am currently trying to merge two Json files - one that is nested and one that is flat:
"ampdata": [
{
"nr": "303",
"code": "JGJGh4958GH",
"Anr": "AVAILABLE",
"ability": [ "" ],
"type": "wheeled",
"conns": [
{
"nr": "447",
"status": "",
"version": "3",
"format": "sckt",
"amp": "32",
"vol": "400",
"vpower": 22
}
]
}
[ {
"nr" : 91643421,
"Anr" : "Real",
"Title" : null,
"Comp" : null,
"Name" : "Smith",
"CompanyName" : "WhiteC"
}]
My current Approach is:
var flowFile = session.get();
if (flowFile != null) {
var StreamCallback = Java.type("org.apache.nifi.processor.io.StreamCallback")
var IOUtils = Java.type("org.apache.commons.io.IOUtils")
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets")
flowFile = session.write(flowFile,
new StreamCallback(function(inputStream, outputStream) {
var text = IOUtils.buffer(inputStream)
var obj = JSON.parse(text)
var neu = [];
var neuesObjekt = {};
for (var i = 0; i < obj.ampdata.length; i++) {
var entry = obj.ampdata[i];
if(obj.ampdata[i].nr != obj2.nr) {
obj2.nr = obj.ampdate[i].nr
}
}
outputStream.write(JSON.stringify(newObj, null, '\t').getBytes(StandardCharsets.UTF_8))
}))
flowFile = session.putAttribute(flowFile, "filename", flowFile.getAttribute('filename').split('.')[0]+'_translated.json')
session.transfer(flowFile, REL_SUCCESS)
How do I parse two flowfiles that are incoming at the same time? I do like to work with both at the same time as I have to compare them at several positions. I can not figure out how I can avoid overwriting the first flowfile.
I had another Approach with using the MergeConent-Processor, but the result was just the concatenation of the both Jsons in a way that was not a valid Json anymore. Anyway I do prefer the Javascript attempt more, I just need your help in figuring out, how to do it in a proper way.
i think you can use merge content with parameters:
merge format: binary
header: [
footer: ]
demarcator: ,
by this merge of two json files into one will produce a valid json (array).
then, if you need to reformat json - you still can use ExecuteScript processor...
and you don't need to implement join files logic.
PS: to get two files from input queue use this type of code:
var flowFiles = session.get(2);
if(!flowFiles)return;
if(flowFiles.size()!=2){
session.transfer(flowFiles); //return files back to input queue
return;
}
//we have exactly two files. let's process them...
var flowFile1 = flowFiles[0];
var flowFile2 = flowFiles[1];
//read each, parse, apply logic, write result
...

Is this a correct JSON string?

I am not quite clear on how to make a JSON string. I get error and I want to find out how to correct and it make it.
This is my JSON string:
var drivers = { "driver" : [
{
"id" : 1,
"name" : "Bob",
"age" : "34"
"car" : [
{
"make" : "BMW",
"model" : "3.20",
"colour" : "Silver"
}
]
},
{
"id" : 2,
"name" : "Rob",
"age" : "22"
"car" : [
{
"make" : "Peugeot",
"model" : "306",
"colour" : "Blue"
}
]
},
{
"id" : 3,
"name" : "Maria",
"age" : "23",
"car" : [
{
"make" : "Mazda",
"model" : "3",
"colour" : "Red"
}
]
}]};
This is the get method:
var driverData = JSON.parse(drivers);
function getDriverData() {
return driverData;
}
return {
getDriverData: getDriverData
};
And in this controller I try to get it so I can see if it works:
var drivers = myDriveApi.getDriverData();
console.log(driverData);
Correct me and explain how to make a JSON string, and I want it nested if that's the right term. So each driver has a car, or multiple cars/vehicles. So if I get 1 driver, I want to see his details and his information on owned vehicles.
Your "JSON string" seems to be JavaScript code that you would have in a script tag that creates a drivers JavaScript object with a property called driver that is an array of other objects. To be JSON, you remove the var drivers = and the semicolon at the end leaving just what you would set a variable to in order to create that object.
For instance, let's say you have a "person" variable that is an object with "firstName" and "lastName" properties. This is code you would put into a script to create that variable:
var person = { firstName: "Jason", lastName: "Goemaat" };
Strings, even JSON strings are represented in scripts surrounded by single or double quotes. To see the string value for the JSON of that object, you can do this:
var json = JSON.stringify(person);
This gives you a valid JSON string which will display this in the console:
{"firstName":"Jason","lastName":"Goemaat"}
To set the variable directly you need to enclose it in single or double quotes, but if the string contains those they would need to be escaped. Since this contains only double quotes I will surround it in single quotes to assign it to a variable in my script, then parse that into an object.
var json = '{"firstName":"Jason","lastName":"Goemaat"}';
var person = JSON.parse(json);
JSON property names need to be surrounded in quotes. Most parsers will work if they are not but it is always better to be as correct as you can be. You can use the online tool at jsonlint to check for valid JSON.
No, that's a JavaScript object, which could be converted to a JSON string using JSON.stringify(object).
If you're trying to access it through JavaScript, you might as well skip JSON altogether and just use the object. If you want to test if a JSON string is good, use jsonlint.com.
It's a JavaScript object, not a JSON string.
You're missing commas after Bob and Rob's age. Maria's all good, though.

Categories

Resources