convert a structured string into array - javascript

this question might have been asked already. But i really have no idea what to search for.
If I have a string like
{{aa:bb,aaa:bbb,cc:ee{{aa:cd,cdc:dd,{{ss:ee}},kk:ee}},se:ff}}
I need to get output in probably in array
ar[0] = aa:bb, ar[1]=aaa:bbb, ar[3] = {{...}}
I tried using variable.split("}}")
which is breaking the string and not getting the actual data.
Is there any recursive function to do this?
I am not able to search because I have no clear idea of what objects,strings.

If you used an existing format for structuring your string, such as JSON:
["aa:bb","aaa:bbb","cc:ee",["aa:cd","cdc:dd",["ss:ee"],"kk:ee"],"se:ff"]
Then you could just run it through JSON.parse(). - It'd be far easier than trying to decode the meaning of that string without being told what it means.

I think what you're looking for is how to parse a JSON string into an object. I'm not certain, but at least it looks like that based on the format of your string. Can you confirm if the source is providing JSON output?
If yes:
Read this other SO question.

Related

parse a string that contains array with strings

I am struggling to parse a string that contains array. And the array also contains list of arrays.
Each of the array contains string.
code here
let a = "[[48934, 'Danial Brendon', 'developer'],[48934, 'Nicki Lopez', 'developer']]";
console.log(JSON.parse(a))
I tried using JSON.parse() but did not work, may be because JSON.parse() also want to parse the string.
I am having difficulty with this even this looks simple. I could not find any similar question/answer like this.
Thanks.
To JSON parse , you need double quotes instead of single. like this ...
let a = '[[48934, "Danial Brendon", "developer"],[48934, "Nicki Lopez", "developer"]]';
console.log(JSON.parse(a));

Weird charaters in a stringified buffer in javascript

I have a particular context in which one data are transformed a lot to get transferred across network. At the end, when I try to get this data back, I have unwanted characters at the beginning of the string.
First, I get the data from a db and it returns it to me as bytes (<Array.<byte>>), fully readable with .toString(). The result is:
{\"company\":\"xxx\",\"email\":\"xxx\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"providerId\":\"xxx\",\"role\":\"xxx\",\"status\":\"xxx\"}
These data are passed to another "environment" with a function (not developed by me and that I cannot change) that returns the data in a "I don't really know what format it is".
I can decode it with the following piece of code:
jsonIdentity = JSON.stringify(bufferIdentity);
Buffer.from(JSON.parse(jsonIdentity).payload.buffer.data).toString('utf-8')
However, at the beginning of the string, I have the following:
"\u0008\u0006\u001a�\u0001\u0008�\u0001\u001a{{\"company\":\"xxx\",\"email\":\"xxx\",\"firstName\":\"xxx\",\"lastName\":\"xxx\",\"providerId\":\"xxx\",\"role\":\"xxx\",\"status\":\"xxx\"}
Also represented like that in my logs:
��{{"company":"xxx","email":"xxx","firstName":"xxx","lastName":"xxx","providerId":"xxx","role":"xxx","status":"xxx"
How can I remove it/prevent it to get in my result? It prevents me from using the JSON.
Update: here is the buffer I get:
{"status":200,"message":"","payload":{"buffer":{"type":"Buffer","data":[8,6,26,128,1,8,200,1,26,123,123,34,99,111,109,112,97,110,121,34,58,34,105,98,109,34,44,34,101,109,97,105,108,34,58,34,102,64,105,98,109,46,99,111,109,34,44,34,102,105,114,115,116,78,97,109,101,34,58,34,102,108,111,114,105,97,110,34,44,34,108,97,115,116,78,97,109,101,34,58,34,99,97,115,116,34,44,34,112,114,111,118,105,100,101,114,73,100,34,58,34,102,99,34,44,34,114,111,108,101,34,58,34,117,115,101,114,34,44,34,115,116,97,116,117,115,34,58,34,111,107,34,125,34,64,98,54,57,51,50,51,53,100,49,52,97,49,98,102,57,57,56,100,50,99,97,102,53,53,52,52,100,97,49,50,50,51,55,101,97,55,99,50,56,55,50,49,56,97,101,55,51,100,55,97,50,53,101,52,55,48,48,51,56,52,100,54,53,54,58,14,100,101,102,97,117,108,116,99,104,97,110,110,101,108]},"offset":10,"markedOffset":-1,"limit":133,"littleEndian":true,"noAssert":false}}
Can you try this out:
const yourString = JSON.parse(jsonIdentity).payload.buffer.data;
console.log(Buffer.from(yourString, 'base64').toString('utf-8'))
An ugly solution would be just trim or replace the characters from your result
Problem fixed. Solution is available on Jira here: https://jira.hyperledger.org/browse/FAB-14785?focusedCommentId=58680&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-58680

JavaScript Encoding & Decoding Error

I am getting an issue with Javascript Encoding and Decoding. I have a json object which contains a string encoded in UTF-8 like 'R\xc3\xa9union'. To ensure that the Javascript file correctly displays the string, I'm adding an attribute charset to the script tag. The json object is in countries.js. I'm including countries.js as <script src="js/countries.js" charset="UTF-8"></script> and yet it is still being displayed as Réunion instead of Réunion. Any suggestion?
Use escape() combined with decodeURIComponent():
decodeURIComponent(escape('R\xc3\xa9union'));
That should do the trick:
escape('R\xc3\xa9union'); // "R%C3%A9union"
decodeURIComponent("R%C3%A9union"); // "Réunion"
Now, you said you couldn't do this manually for all the places you need strings from the JSON. I really don't know a way to automate this without re-building the JSON with JS, so I'd suggest writing a little "wrapper" function to decode on the fly:
function dc(str){
return decodeURIComponent(escape(str));
}
You can then decode the required strings with minimal effort:
var myString = dc(myJson["some"]["value"]);
Now, what else could work, but is a little more risky: JSON.stringify() the entire object, decode that using the 2 functions, then JSON.parse() it again.

How to convert formatted string to regularly javascript dictionary?

I get formatted json string with all \ before " and \n for newlines.How to convert this string to regularly javascript dictionary ?
I thought to replace all \n with '' and \" with " but it is kinda bruteforce solution. Is there moreelegant way ?
It sounds like you're receiving JSON encoded data. To convert the raw data into an object, use the JSON.parse function:
var test = "{\"foo\":\"bar\"}";
var data = JSON.parse(test);
console.log(data);
I am not sure I understand what you mean by 'JavaScript dictionary' exactly but in my experience the easiest way to convert a JSON string to any kind of usable JavaScript object is to use JSON.parse, see Parse JSON in JavaScript? for some good information on this.
Also in future a small sample of what you are trying to do, your source data etc. would be helpful!
It's a escaped string, you should unescape it and using eval will return the object represented by the json string. A JSON string is simply a javascript serialized object, so you may eval'd with javascript and will return the "map" or object that represents.
Newlines are valid in json so you don't require to remove them.
var o = eval("o = {name:\"test\"}");
alert(o.name);
You're probably thinking of a dictionary implementation as you'd find in other languages such as Objective C or C# - JavaScript does not have a dictionary implementation. So is your question how to parse JSON so you can get some values into key value pairs? If so then it sounds like JSON.parse is going to work for you.
If your question is about how to implement something like a dictionary in JavaScript, with data populated from JSON - then you'll want to parse the JSON and set up some simple JavaScript objects to act like a dictionary:
var dictionary = {"key1":"hello", "key2":"hello2", "key3":"hello3"};
console.log(dictionary["key3"]); // gives the value "hello3"

Is this valid JSON?

{"something":"1","mode":"true","number":"1234"}
Because I'm getting a 406 on expecting JSON.
It's being generated via Jersey, which is told that a method #Produces JSON. It's being received by a Dojo xhrGet which has JSON set as its handleAs.
EDIT - To clarify, I'm not interested in the code where I evaluate or anything like that. The question was very simple - is it valid JSON?
It is, but you've got both the boolean (mode) and numeric (number) elements as strings. Shouldn't it be:
{"something":"1","mode":true,"number":1234}
It is valid JSON if all values of the dictionary are Strings. This is also valid JSON:
{"something": 1, "mode": true, "number": 1234}
Usually, however, a 406 error happens when you ask for a response type (such as html or json) and the server cannot send it in that type. Why do you think the input is invalid?
I use a simple copy/paste tool called JASONLint ( http://www.jsonlint.com/ ) to test my mountains of JSON. You may dig it.
If you want to use the numbers directly, you shouldn't put them in quotes. It is valid JSON, but chances are that what you want to do is:
{"something":1,"mode":"true","number":1234}
You need to add more information if you want better answers.
EDIT: Eh... and yes, the boolean shouldn't be quoted either, unless you want to convert it yourself, for some reason.
yes this is valid JSON
although if you're planning on outputting this as the result of a HTTP request, you'll need to escape all the quotes
$str = "{\"something\":\"1\",\"mode\":\"true\",\"number\":\"1234\"}";
echo $str

Categories

Resources