javascript String to JSON? - javascript

I have a string:
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
I want to convert this a to a json data.
How to do it?
I have tried JSON.parse(), but it will raise an error.
SyntaxError: Unexpected token u

That looks like Python literal syntax to me. Tell whoever wrote the Python portion to encode as JSON instead of just outputting the structure as a string.

In this particular case, you can just replace each u'x' with "x" and you'll have valid JSON:
var a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}";
// Convert to JSON (May not work with other inputs!)
var json = a.replace(/u'((?:[^'\\]|\\.)*)'/g, function(a,str){
return '"' + str.replace(/\\'/g, '\'').replace(/"/g, '\\"') + '"';
});
// Parse the JSON into a Javascript object
var obj = JSON.parse(json);
Updated to work with some quotes in the object:
var a = "{u'a':[u'\\'123\\'',u'321'], u'b':[u'456\\\\',u'\"654\"']}";
Becomes:
{a:["'123'","321"], b:["456\",""654""]}

You need to change your input string to a valid JSON string.
I think this is what you wanted:
JSON.parse('{"a":["123","321"], "b":["456","654"]}')

The variables (keys / values ) are strings so need to be in quotes in order to be parsed as valid JSON.
// put quotes around the key / value pairs.
var a = "{\"u'a'\":[\"u'123'\",\"u'321'\"], \"u'b'\":[\"u'456'\",\"u'654'\"]}";
jQuery
a = $.parseJSON(a);

JSON is supposed to contain only strings.
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
Here I can only assume that u is a variable. Change it to this:
a = "{"+u+"'a':["+u+"'123',"+u+"'321'], "+u+"'b':["+u+"'456',"+u+"'654']}"

Related

Converting string to object with Javascript (Error: Unexpected token t in JSON at position 1)

I'm using Editor.js which outputs data as JSON and save that as String in DynamoDB. When I query that data, I want to convert that back to an Object.
Converting the string with JSON.parse() gives me Error: Unexpected token t in JSON at position 1 message.
var json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
obj = JSON.parse(json);
Not sure what this error message means.
I will suggest to correct the JSON from the origin itself if you can,
if you can't than you need to replace = with : and than stringify and parse
({[^=]+|,[^=]+)=
| |_________ Replaces `=` which is preceded by `,`
|_________________ Replaces `=` which is preceded by `{`
let json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
json = json.replace(/({[^=]+|,[^=]+)=/g,"$1"+':')
let obj = JSON.parse(JSON.stringify(json));
console.log(obj)
On side note:- This is code is considering above given example data, it can be updated based on the kind of values your JSON can have

How to properly decode a JSON string encoded using Html.Raw(Json.Encode(Model))?

I am encoding some model data into a html element like this:
#Html.Raw(Json.Encode(Model));
The json string returned looks like this:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
When I try to parse this using JSON.parse, I get an error:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
How do I convert this jsonTestList string into a javascript array so that I can access elements of arrayTestList properly?
Edit:
Sorry, I forgot to mention my edit. Basically above javascript code is inside a Partial View 2. The code where I am json encoding the model is in another Partial View 1. From P V 2, I cannot access the model object of P V 1, so I am just dumping the contents into a div tag, so that I can access this list TestList element.
Try removing this line:
jsonTestList = JSON.stringify(jsonTestList);
jsonTestList is already a JSON string
The issue is now resolved.
I was getting an invalid character, but couldn't immediately recognize which character it was that was causing the problem. I found that my JSON string isn't valid because of the trailing semicolon that was output by the Json.Encode method. I validated the JSON string # http://jsonlint.com.
Once I removed that semicolon, the json string is populated as a JavaScript array into arrayTestList object.
Now just this works, as mentioned in both the answers above, JSON.stringify is not needed.
var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]);
Why are you using Json.Encode? Also in your code, why are you writing redundant code first you are using JSON.stringify and the JSON.parse same object.
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
As per my understanding just Html.Raw will work
In JavaScript
var jsonObject = #Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList = jsonObject.TestList;

Remove part of a JSON

Here is the JSON returned from my Server.
"[{"description":"A user","name":"test","type":"user"}]"
I want to remove the outer double quates. Which means I want the JSON as
[{"description":"A user","name":"test","type":"user"}]
How can I do this? Please help.
You want to turn the JSON into JS objects right? If so, you would do JSON.parse(json). If you need IE7 support, you have to include a polyfill for JSON as it's not supported in IE7<.
You can get the current JSON polyfill here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
As the response from the server is not valid JSON you have to request it as text, fix it, and parse it as JSON. Use dataType: 'text' in your options in the ajax call.
Use the substr method to cut of the first and last character:
data = data.substr(1, data.length - 2);
Then you can parse the JSON:
var obj = $.parseJSON(data);
To strip the first and last character from a string:
var fixed_string = string.substring(1, string.length - 1);
var str = '[{"description":"A user","name":"test","type":"user"}]';
var data = (new Function( "return " +s))();
console.log(f);
In your case response from server is a json string you have to convert it to json object
var str = '[{"description":"A user","name":"test","type":"user"}]';
str = eval('('+str+')');
console.log(str[0].name) //this will give test
Hope this helps.

Convert JSON key value using RegExp

I receive a JSON string from a server call, in this form:
{"0":{"jpgN":"2","spread_value":"392.22","relevant_new":"text"},"1":{"jpgN":"1","spread_value":"395.28","relevant_new":"text"},"count":2}
Using RegExp, is there any way to replace the value of any key jpgN with the string "http://mydomain.com/keyValue.jpg" (eg "http://mydomain.com/2.jpg")?
Replace "jpgN":"([^"]+)" to "jpgN":"http://mydomain.com/$1.jpg".
But it's better to parse json and change values using your programming language.
Something like that ?
var json = {"0":{"jpgN":"2","spread_value":"392.22","relevant_new":"text"},"1":{"jpgN":"1","spread_value":"395.28","relevant_new":"text"},"count":2};
var s = JSON.stringify(json);
s.replace(/\"jpgN\":\"(\w+)\"/g, "\"jpgN\":\"http://mydomain.com/$1.jpg\"");

Can I use a variable to pass a json string?

This code works:
$(this).load($('.pageloadlabel', this).attr('href'), {category: 1});
This code doesn't work:
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), data);
The question is, how can I make it work?
Your data is not a Javascript object but a string, you can convert it to object by eval e.g.
data = eval('(' + data + ')');
but eval is considered dangerous, so better to parse string as JSON e.g.
data = JSON.parse(data)
For JSON lib you can use json2
It's not JSON, it's a javascript object.
var data = { category: 1 };
If you have a string, you would have to convert it to a object.
And notice that your string is not a valid JSON, see the link for more details.
Take out the quotes, the load function is expecting an object, not a string.
Have you tried to use eval() on data?
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), eval(data));

Categories