I have an Object I use JSON.stringify to create JSON string.
Than I save that string into file.
Then I read that file. Make JSON.parse and try to use that object again.
But it does not work anymore.
For example if I use [i] to select element it doesnt select element but just take charset like its a string :(
Can any body help with that?
This is some kind of example but actuall JSON is toooo long:
{"featureCollection":
{"layers":"[
{\"layerDefinition\":
{\"currentVersion\": 10.3,
\"id\": 0,
\"supportsCoordinatesQuantization\": true,
\"advancedQueryCapabilities\":
{
\"supportsPagination\": true,
\"supportsDistinct\": true
},
\"geometryType\":
\"esriGeometryPolygon\", \"minScale\": 0,
\"maxScale\": 0,
\"extent\":
{},
\"drawingInfo\":
{\"renderer\":
{\"type\": \"simple\", \"symbol\":
{\"type\": \"esriSFS\", \"style\": \"esriSFSSolid\", \"color\": [76, 129, 205, 191], \"outline\":
{\"type\": \"esriSLS\", \"style\": \"esriSLSSolid\", \"color\": [0, 0, 0, 255], \"width\": 0.75}
}
},
What's going on is that the layers property of the featureCollection property is not an array, it's a JSON encoding of an array. You need to decode it again to process the contents. Assuming json_obj is the full object, you need to do:
var layers = JSON.parse(json_obj.featureCollection.layers);
Then you can access layers[i].layerDefinition.currentDefinition.
I don't know why it's done that way -- you may want to fix the code that creates the JSON in the first place, and remove the part that calls JSON.stringify() when storing into the layers property.
It looks as though the process that is writing the JSON string to a file is escaping the quotes which is causing the issues when you try to parse. You either need to stop the process from escaping the quotes, or use replace to strip out the escaped quotes of your JSON string prior to passing it to parse
Related
Explanation:
I want to make an Electron app [Javascript not jQuary] (or am in the process of doing so) and would like to add a function that puts one config into the "format" of another.
The big file from which I want to take the information I currently read in via "dialog.showOpenDialog" and can also access the json object.
Now to the problem:
The file I get via the dialog is 8000 lines long and contains individual information that I want to pack into a smaller document with about 3000 lines.
Important: Individual information have a different name e.g. I want "ABCD: 23" from document 1 in the other as EFG: 23.
Now my two questions:
how can I best provide the smaller file for editing?
how can I convert the individual information without going through each line separately?
bigconfig.json:
{
"EXAMPLE_CATEGORY": {
"setting1": 0,
"setting2": 1,
"setting3": 115,
"setting4": 0,
},
Smallerconfig.json
{
"EXAMPLE_CATEGORY": {
"setting7": 115,
"setting8": 0,
},
Edit: What I want to achieve is that I can create (and save) a modified file with the information I packed from the big file into the small one.
In the smaller one should be all 3000 felt
Would really appreciate help... yesterday I did a lot of research and used the search engine for several hours.
Thanks in advance
The only way your smallerConfig object will know which new keys to use is if you define them beforehand. To do this, you must create an object that links the old key names to the new key names. These links would be best defined in one place. The code below holds these links in the conversionTable.
To build the smallerConfig object, you must loop (using for...in) through the bigConfig object one line at a time. Here you will check if the key in the bigConfig object matches a key in the conversionTable (using the in operator). If a matching key is found, then we will use the key’s value in the conversionTable as the new key in the smallerConfig object. Using the bigConfig value in the creation of the smallerConfig object is easy.
let bigConfig = {
'EXAMPLE_CATEGORY': {
'setting1': 0,
'setting2': 1,
'setting3': 115,
'setting4': 0
}
};
let smallerConfig = {
'EXAMPLE_CATEGORY': {}
};
let conversionTable = {
'setting3': 'setting7',
'setting4': 'setting8'
};
// Iterate through the bigConfig object
for (let bigKey in bigConfig.EXAMPLE_CATEGORY) {
// Check for a matching key in the conversionTable
if (bigKey in conversionTable) {
smallerConfig.EXAMPLE_CATEGORY[conversionTable[bigKey]] = bigConfig.EXAMPLE_CATEGORY[bigKey];
}
}
console.log(smallerConfig);
Output will be:
{
'EXAMPLE_CATEGORY': {
'setting7': 115,
'setting8': 0
}
}
Finally:
Use JSON.parse() to convert the file contents from a string to a Javascript object.
Use JSON.stringify() to convert the Javascript object back to a string for writing to the new file.
I am using JSON.stringify on a Json data and after doing this I am getting the " (quotes) at the starting and ending of the data. For eg :
x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}}
after using JSON.stringify i am getting :
x = "{"fieldId":536,"value":{"value":341,"display_value":"ABCD"}}"
but the result I desired is "
x = {"fieldId":536,"value":{"value":341,"display_value":"ABCD"}}
I have tried JSON.parse after stringify but of no use.
If you want an object
In the first code block in your question, you show your JS source code.
In the third code block, you show some more JS source code and say that it is what you want.
The two bits of source code give identical results. They just use very slightly different JavaScript syntax (in an object literal a property name can be an identifier (like foo) or a string (like "foo"), which you use makes no difference to the end result).
If you really do want what is in the third code block, then do nothing.
Do not use JSON.stringify.
If you want JSON
Your second block shows what you say you get after using JSON.stringify.
This result is impossible.
The most likely explanation for this is that you are inspecting the result using a tool which displays a quote before and after the data as a means to indicate to you that the value is a string. The quote characters are not part of the data. You are just misinterpreting what you are seeing.
If you really want a JSON representation of the data in the first code block, then just use JSON.stringify.
var x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}};
var json = JSON.stringify(x);
document.write(json);
I've been banging my head against a wall with this all day, I've looked at other questions and they all say use JSON.parse or something similar, but I can't get anything to work for the life of me.
I have an object stored as text in a PostGres DB:
{149804: [75319, 2887526, 2938701],3136977: [3482061,3482062]}
I have to read it into a variable and go through it's properties but i can't get it to work, if I do a JSON.parse I get a "SyntaxError: Unexpected number" on the first number {1...}.
I tried looking at the object properties without doing a parse to test it, but it keeps saying it doesn't have that property (with and without ' around the number in case):
if(selectedItems.hasOwnProperty(149804)){
console.log("HAS 149804");
}else{
console.log("DOESN'T HAVE 149804");
};
What am I doing wrong here?
That's because your JSON is invalid.
{149804: [75319, 2887526, 2938701],3136977: [3482061,3482062]}
should instead be
{"149804": [75319, 2887526, 2938701],"3136977": [3482061,3482062]}
Then JSON.parse will work. Object properties should be strings, not numbers.
A key name/index in JSON must be a string. Proper JSON would be:
{
"149804": [
75319,
2887526,
2938701
],
"3136977": [
3482061,
3482062
]
}
Is there any way to convert some parts of JSON string to booleans ?
My JSON string example:
{
"file_id": {
"width": "560",
"height": "270",
"esc_button": "1",
"overlay_close": "1",
"overlay_opacity": "1"
}
}
If this was my personal project, I believe I would just convert the output of booleans into true/false strings and not 1 and 0, but since it isn't I wonder if there is a way to set what properties from JSON string are booleans. In this example booleans should be: esc_button, overlay_close but not overlay_opacity...
So since this is JavaScript project, I wonder what are my options and is there any easy way to do this ? There are more settings from this JSON string, I just posted part of it. Settings change depending on click event (different file_id === different settings)
EDIT:
Just figured I could use parseInt(settings[file_id].esc_button) to get boolean, but do I really have to use that all the time ? There might be other ways that I am not aware of.
JSON is just a data format. And if the data you are consuming chose to pass the string "0", you will get the string "0", and not false.
If "0" isn't what you want in your program you need to process the data a bit.
// for example
var processData = function(jsonString) {
var data = JSON.parse(jsonString);
data.esc_button = (data.esc_button == "1");
return data;
};
JSON.parse() itself doesn't provide a way to do this. It just decodes the data as it is in the source. If you need something different, you need to translate.
Ideally you should get your data source to give you this data in a better format. If it has real boolean literal values instead, you don't have to do any translation at all.
{
"file_id": {
"width": 560,
"height": 270,
"esc_button": true,
"overlay_close": false,
"overlay_opacity": 1
}
}
If your JSON looks like that, you just parse it and your done. By removing the quotes from width and height, those are now number values that require no translation to use in other math. And by reporting true or false for boolean values, those will get parsed as boolean literals, not strings. And it all just works.
This also resolves ambiguity. In your original JSON you had "1" for true and "1" for the opacity value, which I assume is expected to be a number form zero to one. Now you can look at the raw JSON data and see the difference.
JS is a dynamic language. You can do it yourself.
if (my_object[its_property]==="1")
my_object[its_property] = true
else
my_object[its_property] = false;
Or more tersely my_object=(my_object[its_property]==="1");.
I'm attempting to parse a JSON string with nested objects received in the response of a post request. After running JSON.parse(responseText), the result is in the following format:
[{
"atco":"43000156407",
"location":{
"longitude":"-1.7876500000000000",
"latitude":"52.4147200000000000","
timestamp":"2013-03-19 11:30:00"
},
"name":"Solihull Station Interchange",
"road":"STATION APPROACH",
"direction":"NA",
"locality":"Solihull",
"town":"Solihull"}, ...
I thought I would then be able pull values out using the following as an example, but all I get is undefined.
var atco = json[0].atco;
I've also tried json[0][0] but that returns an individual character from the JSON ([) . Does this indicate the JSON hasn't parsed correctly, or is this expected behaviour and I'm just referencing incorrectly?
This means that your JSON is being double encoded. Make sure you only encode it once on the server.
As proof, after you've parsed it, parse it again.
var parsed = JSON.parse(resposneText);
var parsed2 = JSON.parse(parsed);
alert(parsed2.atco);
Either that, or you're parsing it but then trying to select the data from the original string. This would obviously not work.