Convert JSON key value using RegExp - javascript

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\"");

Related

Parsing JSON String with JSON.stringify

Trying to parse the JSON content from AWS SQS.
First converting a string to JSON String and then to JSON Object. What is the correct way to handle this scenario ?
<script>
// JSON from SQS
var x='{"Message":"{\"default\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
x1=JSON.stringify(x);
var obj = JSON.parse(x1);
console.log(obj.Message); // undefined
alert(obj["Message"]); // undefined
</script>
I have absolutely no idea why you are trying to JSON.stringify() a string. It's already a string!
The string you have got is not valid JSON either and needs a few extra \\s in it. Where did you get it from? Or was it a typo.
var x='{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
^__________^_____________________________________________________________^
Just parse the JSON you do have then realise that obj.Message is just more JSON that could be JSON.parse()d
// JSON
var x = '{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
//Parse JSON
var obj = JSON.parse(x);
console.log(obj.Message); // string formatted as yet more JSON
The string is not right. It should be like
var x='{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
You are stringifying the x, which is already string
x1=JSON.stringify(x); //Not ok

Expect Object but get String when parsing JSON

I am trying to parse a simple JSON string using jQuery
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
I would expect typeof(parsedJSON.graph_data) to be an Object but instead it is returning string. What is the correct way to return an Object?
It should be like
var parsedJSON = $.parseJSON('{"graph_data": {}}');
console.log(typeof(parsedJSON.graph_data));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
no need of " for object, " is needed for defining string and object key. So it will treat as string here. For more about JSON structure and example visit http://www.json.org/.
try it.
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
console.log(parsedJSON.graph_data);

Javascript: Push Json String to Json object

Im trying to Push a valid json string to javascript json object, but every time im trying to do it like that:
markersData['values'] = [string];
the result is of markersData json object is:
"values":["{'latLng..."
instead of (Original):
"values":[{"latLng...
it take all of the json and push it as one variable (invalid json), how can i push it as a part of the original json?
any idea how to solve it?
Thank you!
You need to deserialise the JSON string before setting it to the property of the object:
markersData['values'] = [JSON.parse(yourJsonString)];
markersData['values'] = [JSON.parse(string)];
Hope this helps.. Read more about JSON.parse here
You need to parse the string first.
JSON.parse(addstringvar);
Code pen demo
var testObj = {};
var addString = '{"name": "test"}';
testObj.values = [JSON.parse(addString)];
You'll need to make sure you have a valid JSON. So below will show you how to create an easy JSON which will be valid for you to use
JSON Object:
var newObject = {};
newObject.Latlng = "ValueHere";
var jsonString = JSON.stringify(newObject);
// Check jsonString before you parse for pushing.
console.log(jsonString);
You will need to deserialise the JSON string before setting it to the
property of the object
like Rory McCrossan mentions in his answer
jsonString[value] = [JSON.parse(jsonString)];

javascript String to JSON?

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']}"

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