How can i convert the below string to JSON using python?
str1 = "{'a':'1', 'b':'2'}"
The json library in python has a function loads which enables you to convert a string (in JSON format) into a JSON. Following code for your reference:
import json
str1 = '{"a":"1", "b":"2"}'
data = json.loads(str1)
print(data)
Note: You have to use ' for enclosing the string, whereas " for the objects and its values.
The string in OP's question is not JSON because the keys and values are enclosed by single-quotes. The function ast.literal_eval can be used to parse this string into a Python dictionary.
import ast
str1 = "{'a':'1', 'b':'2'}"
d = ast.literal_eval(str1)
d["a"] # output is "1"
Other answers like https://stackoverflow.com/a/58540688/5666087 and https://stackoverflow.com/a/58540879/5666087 were able to use the json library because they changed str1 from "{'a':'1', 'b':'2'}" to '{"a":"1", "b":"2"}'. The former is invalid JSON, whereas the latter is valid JSON.
import json
str1 = '{"a":"1", "b":"2"}'
jsonData = json.loads(str1)
print(jsonData["a"])
Reference : LINK
Related
i have a groovy script that runs on Jenkins, i have build there a json object using JsonSlurper
The json object is a nested one, i would need to convert the nested json child into escaped string value instead of a json object (that's the requirement :) ).
{"key1":
{"key2":
{"key3":true}
}
}
Into string escaped value:
{"key1": " {\"key2\":{\"key3\":true}} " }
I'm building the json object by using:
def jsont = new JsonSlurper().parseText(row)
doing some manipulation to the json, then need to convert to string:
jsont.key1 = func(jsont.key1) ----> here i want to convert key1 value to escaped string
Any suggestion?
import groovy.json.*
def json = '''{"key1":
{"key2":
{"key3":true}
}
}
'''
def obj = new JsonSlurper().parseText(json)
obj.key1 = JsonOutput.toJson(obj.key1)
json = JsonOutput.toJson(obj)
result:
{"key1":"{\"key2\":{\"key3\":true}}"}
I am getting this string when we read s3 object as JSON
json_object = s3_client.get_object(Bucket=bucket,Key=json_file_name)
print(json_object)
jsonFileReader = json_object['Body'].read()
jsonDict = json.loads(jsonFileReader)
The data looks like this when i printed
raw = b'"[{\\"timestamp\\": \\"2022-07-27T12:34:52.304000+00:00\\", \\"type\\": \\"ExecutionSucceeded\\", \\"id\\": 9, \\"previousEventId\\": 8, \\"executionSucceededEventDetails\\": {\\"output\\": \\"{\\\\\\"statusCode\\\\\\":200,\\\\\\"body\\\\\\":\\\\\\"\\\\\\\\\\\\\\"Hello from Lambda!\\\\\\\\\\\\\\"\\\\\\"}\\", \\"outputDetails\\": {\\"truncated\\": false}}}]"'
I want to extract type out of it .
But when i do it i get error
status=data[0]['type']
TypeError: string indices must be integers
My code
raw = b'"[{\\"timestamp\\": \\"2022-07-27T12:34:52.304000+00:00\\", \\"type\\": \\"ExecutionSucceeded\\", \\"id\\": 9, \\"previousEventId\\": 8, \\"executionSucceededEventDetails\\": {\\"output\\": \\"{\\\\\\"statusCode\\\\\\":200,\\\\\\"body\\\\\\":\\\\\\"\\\\\\\\\\\\\\"Hello from Lambda!\\\\\\\\\\\\\\"\\\\\\"}\\", \\"outputDetails\\": {\\"truncated\\": false}}}]"'
data = json.loads(raw.decode('utf-8'))
print(data)
print(data[0])
status=data[0]['type']
print(status)
Your decoded raw represents a string, not a json object (notice that the first and last characters of raw are quotes ").
When you do data = json.loads(raw.decode('utf-8')), you have type(data) == str, i.e. data is the string "[{\\"timestamp\\": \\"2022-...", which happens to itself be a json string.
To deserialize this string, json.loads it again:
data = json.loads(data)
And now use it:
print(data[0]['type'])
# prints ExecutionSucceeded
I am trying to get list of json string from given string having multiple json strings separated by ",".
For example
val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"
expected result , List[String] :
["{\"a\":\"b\"}", "{\"c\":\"d\", \"e\":\"f\"}"]
You should replace the json separator with a string or character that is not repeated in the whole string and use that special separator to be used with split method to get you your required output. Here I have used -
jsonString.replace("},{", "}-{").split("-")
You should have output as
res0: Array[String] = Array({"a":"b"}, {"c":"d", "e":"f"})
One step further, calling toList method would get you to the final dataType you require
jsonString.replace("},{", "}-{").split("-").toList //res0: List[String] = List({"a":"b"}, {"c":"d", "e":"f"})
Got solution for it.
val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"
val jsonListString = "[" + jsonString + "]"
val jsonArray = new JSONArray(jsonListString)
This will create array of json.
I need to convert a string json in an object using scala.
I tried this, but I cannot access the prop Name, for example
import scala.util.parsing.json._
val parsed = JSON.parseFull("""{"Name":"abc", "age":10}""")
How can I do to get an string json and convert to an object? Thanks
val parsed = JSON.parseFull("""{"Name":"abc", "age":10}""")
val parsed = JSON.parseFull(parsed)
try it
I am trying to load a Json file from a url and parse it on Python3.4 but i get a few errors and I've no idea what they are pointing to. I did verify the json file on the url from jsonlint.com and the file seems fine. The data.read() is returning 'byte' file and i've type casted it. The code is
import urllib.request
import json
inp = input("enter url :")
if len(inp)<1: inp ='http://python-data.dr-chuck.net/comments_42.json'
data=urllib.request.urlopen(inp)
data_str = str(data.read())
print(type(data_str))
parse_data = json.loads(data_str)
print(type(parse_data))
The error that i'm getting is:
The expression str(data.read()) doesn't "cast" your bytes into a string, it just produces a string representation of them. This can be seen if you print data_str: it's a str beginning with b'.
To actually decode the JSON, you need to do data_str = data.read().decode('utf=8')